BUG: Groupby.transform on datetime with nunique giving incorrect result · Issue #35109 · pandas-dev/pandas (original) (raw)


Note: Please read this guide detailing how to provide the necessary information for us to reproduce your bug.

Code Sample, a copy-pastable example

Your code here

import pandas as pd bdates = pd.bdate_range('2008-12-31', '2011-12-30') df = pd.DataFrame(bdates, columns=['date']) df['year'] = df['date'].dt.year df.groupby('year')['date'].transform('nunique') 0 1970-01-01 00:00:00.000000001 1 1970-01-01 00:00:00.000000261 2 1970-01-01 00:00:00.000000261 3 1970-01-01 00:00:00.000000261 4 1970-01-01 00:00:00.000000261 ...
778 1970-01-01 00:00:00.000000260 779 1970-01-01 00:00:00.000000260 780 1970-01-01 00:00:00.000000260 781 1970-01-01 00:00:00.000000260 782 1970-01-01 00:00:00.000000260 Name: date, Length: 783, dtype: datetime64[ns]

Problem description

The current behaviour returns the sum of default timestamp with the number of unique count of dates in each year. The expected output should have been the number of unique counts for the date in each year which is consistent with the behavior of other Groupby.transform functions.

Expected Output

Your code here

import pandas as pd bdates = pd.bdate_range('2008-12-31', '2011-12-30') df = pd.DataFrame(bdates, columns=['date']) df['year'] = df['date'].dt.year df.groupby('year')['date'].transform('nunique') 0 1 1 261 2 261 3 261 4 261 ...
778 260 779 260 780 260 781 260 782 260 Name: date, Length: 783, dtype: int

Output of pd.show_versions()

INSTALLED VERSIONS

commit : None
python : 3.7.7.final.0
python-bits : 64
OS : Linux
OS-release : 4.14.181-140.257.amzn2.x86_64
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.0.4
numpy : 1.18.5
pytz : 2020.1
dateutil : 2.8.1
pip : 20.0.2
setuptools : 47.1.1.post20200604
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.11.2
IPython : 7.15.0
pandas_datareader: None
bs4 : None
bottleneck : None
fastparquet : None
gcsfs : None
lxml.etree : None
matplotlib : 3.2.1
numexpr : 2.7.1
odfpy : None
openpyxl : 3.0.4
pandas_gbq : None
pyarrow : 0.17.1
pytables : None
pytest : None
pyxlsb : None
s3fs : None
scipy : 1.4.1
sqlalchemy : None
tables : None
tabulate : 0.8.7
xarray : None
xlrd : None
xlwt : None
xlsxwriter : None
numba : None