-
-
Notifications
You must be signed in to change notification settings - Fork 18.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
crosstab gives wrong result if a categorical Series contains NaNs #21565
Comments
Curiously, the behaviour changes if one uses
Now, the two outputs are the same. (Alhough: Shouldn't they contain a row for NA?) Note also, how in the example above (without |
Thanks, this looks to be the same underlying issue as #21133, which was fixed by #21252. Upgrading to 0.23.1 should give you the expected behavior: In [2]: pd.__version__
Out[2]: '0.23.1'
In [3]: df = pd.DataFrame.from_dict({"objcol": ("A", "B", np.nan, "C", "C", "A", "D" )})
...: df["catcol"] = df.objcol.astype('category')
In [4]: pd.crosstab( df.catcol, 1 )
Out[4]:
col_0 1
catcol
A 2
B 1
C 2
D 1
In [5]: pd.crosstab( df.objcol, 1 )
Out[5]:
col_0 1
objcol
A 2
B 1
C 2
D 1 |
Issue is still present in 0.23.4 |
@aganatramoat : please provide a reproducible example, as this appears to be working fine on 0.23.4: In [1]: import pandas as pd; import numpy as np; pd.__version__
Out[1]: '0.23.4'
In [2]: df = pd.DataFrame.from_dict({"objcol": ("A", "B", np.nan, "C", "C", "A", "D" )})
...: df["catcol"] = df.objcol.astype('category')
...:
In [3]: pd.crosstab(df.catcol, 1)
Out[3]:
col_0 1
catcol
A 2
B 1
C 2
D 1
In [4]: pd.crosstab(df.objcol, 1)
Out[4]:
col_0 1
objcol
A 2
B 1
C 2
D 1 |
Sorry misspoke, the problem is with crosstab with categorical data and margins.
On one run of the above, I get
The margins are permuted |
Test code:
Problem description
We have this data frame:
The first column is of dtype object, the second column of dtype 'category'. Running
crosstab
on the two columns gives different results:Clearly, the second result is wrong. Note how "C" has the wrong count, 1 instead of 2.
value_counts
, on the other hand, works correctly:Expected Output
pd.crosstab( df.catcol, 1 )
should give the same output aspd.crosstab( df.objcol, 1 )
.Output of
pd.show_versions()
pandas: 0.23.0
pytest: None
pip: 10.0.1
setuptools: 39.2.0
Cython: None
numpy: 1.14.3
scipy: 1.1.0
pyarrow: None
xarray: None
IPython: 6.4.0
sphinx: None
patsy: 0.5.0
dateutil: 2.7.3
pytz: 2014.10
blosc: None
bottleneck: None
tables: 3.4.3
numexpr: 2.6.5
feather: None
matplotlib: 2.2.2
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: 0.7.3
lxml: None
bs4: None
html5lib: 1.0.1
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: 2.10
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None
The text was updated successfully, but these errors were encountered: