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: Inconsistent assignment of NAT values to datetime columns in MultiIndex #43351

Open
2 of 3 tasks
galipremsagar opened this issue Sep 1, 2021 · 7 comments
Open
2 of 3 tasks
Labels
Bug Datetime Datetime data dtype Missing-data np.nan, pd.NaT, pd.NA, dropna, isnull, interpolate MultiIndex Regression Functionality that used to work in a prior pandas version Timedelta Timedelta data type

Comments

@galipremsagar
Copy link

  • 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.


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

Code Sample, a copy-pastable example

>>> import pandas as pd
>>> import numpy as np
>>> midx = pd.MultiIndex(
...         [
...             ["a", "b", "c"],
...             ["house", "store", "forest"],
...             ["clouds", "clear", "storm"],
...             ["fire", "smoke", "clear"],
...             [
...                 np.datetime64("2001-01-01", "ns"),
...                 np.datetime64("2002-01-01", "ns"),
...                 np.datetime64("2003-01-01", "ns"),
...             ],
...             [1.0, np.nan, 2],
...         ],
...         [
...             [0, 0, 0, 0, 1, 1, 2],
...             [1, 1, 1, 1, 0, 0, 2],
...             [0, 0, 2, 2, 2, 0, 1],
...             [0, 0, 0, 1, 2, 0, 1],
...             [1, 0, 1, 2, 0, 0, 1],
...             [1, 0, 1, 2, 0, 0, 1],
...         ],
...     )
>>> midx.names = ["alpha", "location", "weather", "sign", "timestamp", "float"]
>>> 
>>> pdf = pd.DataFrame({'a':[1] , 'b':[2] , 'c':[3] , 'd':[2] , 'e':[0] , 'f':[2], 'g':[10]})
>>> pdf.columns = midx
>>> pdf
alpha              a                                           b                     c
location       store                                       house                forest
weather       clouds                 storm                 storm     clouds      clear
sign            fire                  fire      smoke      clear       fire      smoke
timestamp 2002-01-01 2001-01-01 2002-01-01 2003-01-01 2001-01-01 2001-01-01 2002-01-01
float            NaN        1.0        NaN        2.0        1.0        1.0        NaN
0                  1          2          3          2          0          2         10
>>> pdf["new_col"] = [11]
>>> pdf
alpha              a                                           b                     c new_col
location       store                                       house                forest        
weather       clouds                 storm                 storm     clouds      clear        
sign            fire                  fire      smoke      clear       fire      smoke        
timestamp 2002-01-01 2001-01-01 2002-01-01 2003-01-01 2001-01-01 2001-01-01 2002-01-01     NaT
float            NaN        1.0        NaN        2.0        1.0        1.0        NaN        
0                  1          2          3          2          0          2         10      11
>>> pdf.columns
MultiIndex([(      'a',  'store', 'clouds',  'fire', '2002-01-01', nan),
            (      'a',  'store', 'clouds',  'fire', '2001-01-01', 1.0),
            (      'a',  'store',  'storm',  'fire', '2002-01-01', nan),
            (      'a',  'store',  'storm', 'smoke', '2003-01-01', 2.0),
            (      'b',  'house',  'storm', 'clear', '2001-01-01', 1.0),
            (      'b',  'house', 'clouds',  'fire', '2001-01-01', 1.0),
            (      'c', 'forest',  'clear', 'smoke', '2002-01-01', nan),
            ('new_col',       '',       '',      '',        'NaT',  '')],
           names=['alpha', 'location', 'weather', 'sign', 'timestamp', 'float'])

Problem description

It looks like just for datetime like types the NAT values are being inserted in multiIndex, and not for string or float types.

Previous behavior in 1.2.5 was consistent with all types, i.e., just insert empty string ''

[this should explain why the current behaviour is a problem and why the expected output is a better solution]

Expected Output

Consistency with all dtypes as in 1.2.5

Output of pd.show_versions()

INSTALLED VERSIONS

commit : 5f648bf
python : 3.8.10.final.0
python-bits : 64
OS : Linux
OS-release : 4.15.0-76-generic
Version : #86-Ubuntu SMP Fri Jan 17 17:24:28 UTC 2020
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.3.2
numpy : 1.21.2
pytz : 2021.1
dateutil : 2.8.2
pip : 21.2.4
setuptools : 57.4.0
Cython : 0.29.24
pytest : 6.2.5
hypothesis : 6.17.4
sphinx : 4.1.2
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.0.1
IPython : 7.27.0
pandas_datareader: None
bs4 : 4.9.3
bottleneck : None
fsspec : 2021.08.1
fastparquet : None
gcsfs : None
matplotlib : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : 5.0.0
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : 0.53.1

@galipremsagar galipremsagar added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Sep 1, 2021
simonjayhawkins added a commit to simonjayhawkins/pandas that referenced this issue Sep 5, 2021
@simonjayhawkins
Copy link
Member

simonjayhawkins commented Sep 5, 2021

Thanks @galipremsagar for the report.

Previous behavior in 1.2.5 was consistent with all types, i.e., just insert empty string ''

first bad commit: [412554b] BUG/API: DTI/TDI/PI.insert cast to object on failure (#39068)

cc @jbrockmendel

I'm not sure that the 1.2.5 behavior is correct, it returns a Series whereas partial indexing on the first level returns a DataFrame for the other labels, including c which is a single column DataFrame. I also would have expected the numeric level to have a np.nan rather than a empty string and the returned index on master to include all levels.

EDIT: the behavior I refer to above is the return value of pdf["new_col"] which is not in the code sample.

@simonjayhawkins simonjayhawkins added MultiIndex Regression Functionality that used to work in a prior pandas version Datetime Datetime data dtype and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Sep 5, 2021
@simonjayhawkins simonjayhawkins added this to the 1.3.3 milestone Sep 5, 2021
@jbrockmendel
Copy link
Member

I also would have expected the numeric level to have a np.nan rather than a empty string

I think this boils down to the fact that pd.Timestamp("") returns NaT while float("") raises. Off the top of my head I can't think of a way to do this that isn't either a) pretty invasive or b) using casting logic in Index.insert different from everywhere else

@simonjayhawkins
Copy link
Member

Thanks @jbrockmendel for looking into this. will move to 1.3.4

@simonjayhawkins simonjayhawkins modified the milestones: 1.3.3, 1.3.4 Sep 11, 2021
@mroeschke mroeschke added the Missing-data np.nan, pd.NaT, pd.NA, dropna, isnull, interpolate label Sep 30, 2021
@simonjayhawkins
Copy link
Member

changing milestone to 1.3.5

@simonjayhawkins simonjayhawkins modified the milestones: 1.3.4, 1.3.5 Oct 16, 2021
@jreback
Copy link
Contributor

jreback commented Nov 28, 2021

good to fix but not necessary for 1.3.x

@simonjayhawkins
Copy link
Member

moving off 1.3.x milestone

@simonjayhawkins simonjayhawkins modified the milestones: 1.3.5, Contributions Welcome Dec 11, 2021
@hagenw
Copy link

hagenw commented Jul 27, 2022

The same behavior happens for np.timedelta64

@simonjayhawkins simonjayhawkins added the Timedelta Timedelta data type label Jul 27, 2022
@mroeschke mroeschke removed this from the Contributions Welcome milestone Oct 13, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Datetime Datetime data dtype Missing-data np.nan, pd.NaT, pd.NA, dropna, isnull, interpolate MultiIndex Regression Functionality that used to work in a prior pandas version Timedelta Timedelta data type
Projects
None yet
Development

No branches or pull requests

6 participants