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: Result of pd.concat([], keys=) with identical key has trouble with MultiIndex .loc[] #46519

Closed
3 tasks done
kwhkim opened this issue Mar 26, 2022 · 2 comments · Fixed by #46546
Closed
3 tasks done
Labels
Bug MultiIndex Reshaping Concat, Merge/Join, Stack/Unstack, Explode
Milestone

Comments

@kwhkim
Copy link
Contributor

kwhkim commented Mar 26, 2022

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

df1 = pd.DataFrame(
  {'name':["김희선","김희선", "박보검"],
  'date':pd.to_datetime(['2022-01-02', '2022-01-03', '2022-01-04']),
  'product':["바지","샴푸", "샴푸"]}  
)
df2 = pd.DataFrame(
  {'name' :["김희선","박보검"],
   'date':pd.to_datetime(['2022-04-01', '2022-04-15']),
   'product':["텔레비전","바지"]}  
)
df3 = pd.DataFrame(
  {"name":["비회원", "김수현"],
  "date":pd.to_datetime(['2022-05-01', '2022-05-25']),
  "product":["바지","텔레비전"]}
)
dat = pd.concat([df1, df2, df3], keys=['dfA', 'dfB', 'dfA'])
dat.loc[("dfA", 0),:]

dfAll = pd.DataFrame(
  {'name':["김희선","김희선", "박보검",
           "김희선","박보검", 
           "비회원","김수현"],
  'date':pd.to_datetime(['2022-01-02', '2022-01-03', '2022-01-04',
                        '2022-04-01', '2022-04-15',
                        '2022-05-01', '2022-05-25']),
  'product':["바지","샴푸", "샴푸",
            "텔레비전","바지",
            "바지","텔레비전"]}  ,
    index = [['dfA', 'dfA', 'dfA', 'dfB', 'dfB', 'dfA', 'dfA'],
            [0,1,2,0,1,0,1]]
)

Issue Description

The result from pd.concat([,,,], keys=[]) with identical key name does not allow multi-level indexing

Expected Behavior

dat.loc[("dfA", 0),:] should be

         	  name	date	product
dfA	0	김희선	2022-01-02	바지
            0	비회원	2022-05-01	바지

just like datAll.loc[("dfA", 0),:]
instead of generating KeyError: 'dfA'

or maybe prevent users from using pd.concat([], keys=[]) with identical key.

Installed Versions

INSTALLED VERSIONS

commit : 06d2301
python : 3.8.12.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.19044
machine : AMD64
processor : Intel64 Family 6 Model 94 Stepping 3, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : Korean_Korea.949

pandas : 1.4.1
numpy : 1.22.2
pytz : 2021.3
dateutil : 2.8.2
pip : 22.0.3
setuptools : 60.9.3
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.8.0
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.0.3
IPython : 8.0.1
pandas_datareader: None
bs4 : 4.10.0
bottleneck : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.5.1
numba : None
numexpr : 2.8.1
odfpy : None
openpyxl : 3.0.9
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : 1.0.9
s3fs : None
scipy : 1.8.0
sqlalchemy : None
tables : 3.7.0
tabulate : None
xarray : None
xlrd : 2.0.1
xlwt : None
zstandard : None

@kwhkim kwhkim added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Mar 26, 2022
@rhshadrach
Copy link
Member

rhshadrach commented Mar 28, 2022

Thanks for the report! This appears to be a bug in concat; the simplified example:

df1 = pd.DataFrame({'name': ["a", "a", "b"]})
df2 = pd.DataFrame({'name': ["a", "b"]})
df3 = pd.DataFrame({"name": ["c", "d"]})
dat = pd.concat([df1, df2, df3], keys=['x', 'y', 'x'])
dat.loc[("x", 0),:]

gives the same error as yours on main, but it does not occur if I recreate the frame directly:

df = (
    pd.DataFrame({'a': ['x', 'x', 'x', 'y', 'y', 'x', 'x'], 'b': [0, 1, 2, 0, 1, 0, 1], 'name': list('aababcd')})
    .set_index(['a' ,'b'])
)
df.index.names = [None, None]
df.loc[('x', 0), :]

@rhshadrach rhshadrach added Reshaping Concat, Merge/Join, Stack/Unstack, Explode and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Mar 28, 2022
@rhshadrach rhshadrach added this to the Contributions Welcome milestone Mar 28, 2022
@kwhkim
Copy link
Contributor Author

kwhkim commented Mar 28, 2022

It really needs some inspection because I do not get how this can happen

see the below

df == dat
# all True
df.index.get_level_values(0) == dat.index.get_level_values(0)
# array([ True,  True,  True,  True,  True,  True,  True])
df.index.get_level_values(1) == dat.index.get_level_values(1)
# array([ True,  True,  True,  True,  True,  True,  True])
dat.equals(df)
# True

@jreback jreback modified the milestones: Contributions Welcome, 1.5 Mar 29, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug MultiIndex Reshaping Concat, Merge/Join, Stack/Unstack, Explode
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants