Skip to content
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

BUG: Column of dtype Categorical in DataFrame encounters error when taking a row that includes nan in the column #58954

Open
2 of 3 tasks
cinntamani opened this issue Jun 7, 2024 · 5 comments
Labels
Bug Categorical Categorical Data Type Indexing Related to indexing on series/frames, not to indexes themselves

Comments

@cinntamani
Copy link

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import numpy as np
import pandas as pd

df2 = pd.DataFrame({'a': [1, 2], 'b': pd.Categorical([3, np.nan])})
df2.dtypes
df2.iloc[0, :] # The series has dtype int
df2.iloc[1, :] # ValueError: cannot convert float NaN to integer

df2 = pd.DataFrame({'a': [1., 2.], 'b': pd.Categorical([3, np.nan])})
df2.dtypes
df2.iloc[0, :] # The series has dtype float
df2.iloc[1, :] # OK, because the first column is float

df2 = pd.DataFrame({'a': [1, 2], 'b': pd.Series([3, np.nan], dtype=object)})
df2.dtypes
df2.iloc[0, :] # The series has dtype object
df2.iloc[1, :] # OK, because the Series of dtype object can hold mixed element type

Issue Description

When columns are created as pd.Categorical, taking a row out sometimes encounter strange error, because a row is of type pd.Series, which has to take a fixed type for all the elements. If there is np.nan in the row, it might throw error if the earlier column is of type int. Would it make sense to make the row ALWAYS take dtype object, because it is very common to have mixed types as row ALWAYS spans different columns?

Expected Behavior

Taking a row out of a DataFrame that has a pd.Categorical column should not report inconsistent error, depending on what earlier columns are present.

Installed Versions

INSTALLED VERSIONS

commit : ba1cccd
python : 3.11.5.final.0
python-bits : 64
OS : Darwin
OS-release : 23.4.0
Version : Darwin Kernel Version 23.4.0: Fri Mar 15 00:10:42 PDT 2024; root:xnu-10063.101.17~1/RELEASE_ARM64_T6000
machine : arm64
processor : arm
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 2.1.0
numpy : 1.25.2
pytz : 2023.3
dateutil : 2.8.2
setuptools : 65.5.0
pip : 24.0
Cython : None
pytest : 7.4.0
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.9.3
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.1.2
IPython : 8.14.0
pandas_datareader : None
bs4 : 4.12.2
bottleneck : None
dataframe-api-compat: None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.8.2
numba : None
numexpr : None
odfpy : None
openpyxl : 3.1.2
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.11.2
sqlalchemy : None
tables : None
tabulate : 0.9.0
xarray : None
xlrd : None
zstandard : None
tzdata : 2023.3
qtpy : None
pyqt5 : None

@cinntamani cinntamani added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Jun 7, 2024
@rhshadrach
Copy link
Member

Thanks for the report - confirmed on main. Further investigations and PRs to fix are welcome!

@rhshadrach rhshadrach added Indexing Related to indexing on series/frames, not to indexes themselves Categorical Categorical Data Type and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Jun 8, 2024
@ai-naymul
Copy link

Pandas version checks

  • I have checked that this issue has not already been reported.
  • I have confirmed this bug exists on the latest version of pandas.
  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import numpy as np
import pandas as pd

df2 = pd.DataFrame({'a': [1, 2], 'b': pd.Categorical([3, np.nan])})
df2.dtypes
df2.iloc[0, :] # The series has dtype int
df2.iloc[1, :] # ValueError: cannot convert float NaN to integer

df2 = pd.DataFrame({'a': [1., 2.], 'b': pd.Categorical([3, np.nan])})
df2.dtypes
df2.iloc[0, :] # The series has dtype float
df2.iloc[1, :] # OK, because the first column is float

df2 = pd.DataFrame({'a': [1, 2], 'b': pd.Series([3, np.nan], dtype=object)})
df2.dtypes
df2.iloc[0, :] # The series has dtype object
df2.iloc[1, :] # OK, because the Series of dtype object can hold mixed element type

Issue Description

When columns are created as pd.Categorical, taking a row out sometimes encounter strange error, because a row is of type pd.Series, which has to take a fixed type for all the elements. If there is np.nan in the row, it might throw error if the earlier column is of type int. Would it make sense to make the row ALWAYS take dtype object, because it is very common to have mixed types as row ALWAYS spans different columns?

Expected Behavior

Taking a row out of a DataFrame that has a pd.Categorical column should not report inconsistent error, depending on what earlier columns are present.

Installed Versions

Hey,

Could you please try the following code in your machine:

import pandas as pd

# Explicitly setting dtype to object for columns that might contain mixed types
df2 = pd.DataFrame({'a': np.array([1, 2], dtype=object), 
                    'b': pd.Categorical([3, np.nan], categories=[3], ordered=False)})
print(df2.dtypes)
print(df2.iloc[0, :])  
print(df2.iloc[1, :])  ```

@cinntamani
Copy link
Author

Here is the output on my machine:

a      object
b    category
dtype: object
a    1
b    3
Name: 0, dtype: object
a      2
b    NaN
Name: 1, dtype: object

Thank you!

@samyukta-31
Copy link

Hi! I would like to attempt this issue if that's alright. :)

@samyukta-31
Copy link

samyukta-31 commented Jul 17, 2024

Initial thoughts -

  1. np.nan cannot be coerced into an integer. If either the column it belongs to has float or the row it belongs to has float, it does not throw the error - rather its datatype becomes float as well

pd.DataFrame({'a': [1, 2], 'b': pd.Categorical([3.0, np.nan])}).iloc[1, :] # No error
pd.DataFrame({'a': [1.0, 2.0], 'b': pd.Categorical([3, np.nan])}).iloc[1, :] # No error
pd.DataFrame({'a': [1, 2], 'b': pd.Categorical([3, np.nan])}).iloc[1, :] # Error

  1. The issue repeats for None, np.datetime64('NaT') and pd.NA as well
  2. The issue repeats for pd.DataFrame({'a': [1, 2], 'b': pd.Series([3, np.nan], dtype="category")}).iloc[1, :], as well as for dtype=int (which is expected since np.nan is not an integer), but does not occur for dtpe='string', since string dtype inherently is compatible with pd.NA and therefore converts all nan values to pd.NA

Therefore the easiest way to fix this seems to be to make any column containing a Nan into an object datatype (that can accommodate heterogenous datatypes) within pandas/core/arrays/categorical.py. This however may have some performance implications, so would love to hear some thoughts on what you think the trade offs might be.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Categorical Categorical Data Type Indexing Related to indexing on series/frames, not to indexes themselves
Projects
None yet
Development

No branches or pull requests

4 participants