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

REGR: ValueError: cannot convert float NaN to integer - on dataframe.reset_index() in pandas 1.1.0 #35606

Closed
2 of 3 tasks
ndhansen opened this issue Aug 7, 2020 · 5 comments · Fixed by #35673
Closed
2 of 3 tasks
Labels
Bug Datetime Datetime data dtype MultiIndex Regression Functionality that used to work in a prior pandas version
Milestone

Comments

@ndhansen
Copy link

ndhansen commented Aug 7, 2020

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

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

  • (optional) I have confirmed this bug exists on the master branch of pandas.


Code Sample, a copy-pastable example

from pandas.core.dtypes.cast import construct_1d_arraylike_from_scalar
from pandas.core.dtypes.missing import na_value_for_dtype
import numpy as np

dtype = np.datetime64().dtype
length = 10
works_value = np.NaN
fails_value = na_value_for_dtype(dtype)

# works
construct_1d_arraylike_from_scalar(works_value, length, dtype)

# fails
construct_1d_arraylike_from_scalar(fails_value, length, dtype)

Results in:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
    construct_1d_arraylike_from_scalar(value, length, dtype)
  File "/usr/lib/python3.8/site-packages/pandas/core/dtypes/cast.py", line 1453, in construct_1d_arraylike_from_scalar
    subarr.fill(value)
ValueError: cannot convert float NaN to integer

Problem description

This is a problem was found when calling reset_index on a MultiIndex Dataframe with an index containing datetime information. The expected behaviour would be that it would return an array of NaTs, which ironically only happens if you pass it np.NaN.
I'm not familiar with the source code of numpy, so I can only speculate on how to fix it, but I would assume we would need special handling for time values, so we fill time arrays with np.NaNs instead of pandas._libs.tslibs.nattype.NaTTypes.

Expected Output

array(['NaT', 'NaT', 'NaT', 'NaT', 'NaT', 'NaT', 'NaT', 'NaT', 'NaT', 'NaT'], dtype=datetime64)

Output of pd.show_versions()

INSTALLED VERSIONS

commit : None
python : 3.8.3.final.0
python-bits : 64
OS : Linux
OS-release : 5.7.9-1-MANJARO
machine : x86_64
processor :
byteorder : little
LC_ALL : None
LANG : en_GB.UTF-8
LOCALE : en_GB.UTF-8

pandas : 1.0.5
numpy : 1.19.1
pytz : 2020.1
dateutil : 2.8.1
pip : 20.1.1
setuptools : 49.2.0
Cython : 0.29.21
pytest : 5.4.3
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.5.2
html5lib : 1.1
pymysql : None
psycopg2 : None
jinja2 : 2.11.2
IPython : 7.16.1
pandas_datareader: 0.10.0dev0
bs4 : 4.9.1
bottleneck : 1.3.2
fastparquet : None
gcsfs : None
lxml.etree : 4.5.2
matplotlib : 3.3.0
numexpr : 2.7.1
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pytables : None
pytest : 5.4.3
pyxlsb : None
s3fs : None
scipy : 1.5.1
sqlalchemy : 1.3.17
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
xlsxwriter : None
numba : None

@ndhansen ndhansen added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Aug 7, 2020
@simonjayhawkins
Copy link
Member

This is a problem was found when calling reset_index on a MultiIndex Dataframe with an index containing datetime information.

can you post a small code sample of this (i.e bug arising using the pandas public API)

@simonjayhawkins simonjayhawkins added Needs Info Clarification about behavior needed to assess issue and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Aug 7, 2020
@ndhansen
Copy link
Author

Sure.

import pandas as pd
import datetime
df = pd.DataFrame({'a': [datetime.date(2020, 7, 20), datetime.date(2020, 7, 20)], 'b': [3, 4], 'c': [2.0, 3.0], 'd': [5, 4]})
df = df.set_index(['a', 'b'])
df = df[df['c'] == 1]
df.reset_index()

@simonjayhawkins
Copy link
Member

Thanks @ndhansen for the example. so this issue is that there are unused codes in the MultiIndex

>>> pd.__version__
'1.2.0.dev0+67.gaefae55e1'
>>>
>>> idx = index = pd.MultiIndex.from_tuples([], names=["a", "b"])
>>> df = pd.DataFrame(index=idx, columns=["c", "d"])
>>> df.reset_index()
Empty DataFrame
Columns: [a, b, c, d]
Index: []
>>>
>>> idx = pd.MultiIndex(
...     levels=[[pd.Timestamp("2020-07-20 00:00:00")], [3, 4]],
...     codes=[[], []],
...     names=["a", "b"],
... )
>>> df = pd.DataFrame(index=idx, columns=["c", "d"])
>>> df.reset_index()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\simon\pandas\pandas\core\frame.py", line 4861, in reset_index
    level_values = _maybe_casted_values(lev, lab)
  File "C:\Users\simon\pandas\pandas\core\frame.py", line 4794, in _maybe_casted_values
    values = construct_1d_arraylike_from_scalar(
  File "C:\Users\simon\pandas\pandas\core\dtypes\cast.py", line 1555, in construct_1d_arraylike_from_scalar
    subarr.fill(value)
ValueError: cannot convert float NaN to integer
>>>

and this was working in 1.0.5

>>> pd.__version__
'1.0.5'
>>>
>>> idx = pd.MultiIndex(
...     levels=[[pd.Timestamp("2020-07-20 00:00:00")], [3, 4]],
...     codes=[[], []],
...     names=["a", "b"],
... )
>>> df = pd.DataFrame(index=idx, columns=["c", "d"])
>>> df.reset_index()
Empty DataFrame
Columns: [a, b, c, d]
Index: []
>>>

@simonjayhawkins simonjayhawkins added MultiIndex Regression Functionality that used to work in a prior pandas version Datetime Datetime data dtype and removed Needs Info Clarification about behavior needed to assess issue labels Aug 10, 2020
@simonjayhawkins simonjayhawkins added this to the 1.1.1 milestone Aug 10, 2020
@simonjayhawkins
Copy link
Member

and this was working in 1.0.5

hmm #35111

efcf4b4 is the first bad commit
commit efcf4b4
Author: Simon Hawkins simonjayhawkins@gmail.com
Date: Mon Jul 6 21:55:02 2020 +0100

BUG: reset_index is passing a bad dtype to NumPy (#35111)

@simonjayhawkins
Copy link
Member

changing title to make issue more discoverable

@simonjayhawkins simonjayhawkins changed the title BUG: construct_1d_arraylike_from_scalar does not handle NaT correctly REGR: ValueError: cannot convert float NaN to integer - on dataframe.reset_index() in pandas 1.1.0 Aug 11, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Datetime Datetime data dtype MultiIndex Regression Functionality that used to work in a prior pandas version
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants