DataFrame.nunique and Series.nunique not consistent when Empty · Issue #28202 · pandas-dev/pandas (original) (raw)
Code Sample, a copy-pastable example if possible
Example A:
import pandas as pd df = pd.DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]}) assert df.nunique().tolist() == [df[col].nunique() for col in df.columns]
Both equal [2, 2, 2]
Example B:
df = pd.DataFrame(columns=['a', 'b', 'c']) df.nunique()
Empty DataFrame
Columns: [a, b, c]
Index: []
[df[col].nunique() for col in df.columns]
[0, 0, 0]
Problem description
In Example A, when a DataFrame isn't empty, getting nunique is consistent between the DataFrame and Series approaches; however, when a DataFrame is empty (Example B), DataFrame.nunique returns itself, while the Series approach returns 0.
Expected Output
I would expect df.nunique to return 0 for each column, consistent with how a Series behaves. An empty object, by definition, has 0 unique elements in my mind.
Output of pd.show_versions()
[paste the output of pd.show_versions()
here below this line]
INSTALLED VERSIONS
commit : None
python : 3.6.5.final.0
python-bits : 64
OS : Darwin
OS-release : 18.7.0
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8
pandas : 0.25.0
numpy : 1.17.0
pytz : 2019.2
dateutil : 2.8.0
pip : 18.1
setuptools : 41.1.0
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : 7.7.0
pandas_datareader: None
bs4 : None
bottleneck : None
fastparquet : None
gcsfs : None
lxml.etree : None
matplotlib : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pytables : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
xarray : None
xlrd : None
xlwt : None
xlsxwriter : None
Thank you!