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

ENH: Is possible use rename for flatten MultiIndex? #34254

Open
jesrael opened this issue May 19, 2020 · 2 comments
Open

ENH: Is possible use rename for flatten MultiIndex? #34254

jesrael opened this issue May 19, 2020 · 2 comments

Comments

@jesrael
Copy link

jesrael commented May 19, 2020

From SO:

df1 = (df.set_index(['Animal', df.groupby('Animal').cumcount().add(1)])
         .unstack()
         .sort_index(axis=1, level=1))
df1.columns = [f'{a}_{b}' for a, b in df1.columns]
df1 = df1.reset_index()
print (df1)
  Animal  Age_1 Color_1 Length_1  Age_2 Color_2 Length_2  Age_3 Color_3  \
0    Cat      1   Brown     50cm      2   White     60cm      3   Brown   
1    Dog      1   White     99cm      2   White    129cm      3   White   

  Length_3  
0     55cm  
1    105cm  

If I want chain flatten MultIindex for one line solution, is it possible? Now f-strings cannot chain with sort_index and reset_index (or not idea how).

Is possible implemented MultiIndex.to_flat_index for DataFrame ?

df1 = (df.set_index(['Animal', df.groupby('Animal').cumcount().add(1)])
         .unstack()
         .sort_index(axis=1, level=1)
         .to_flat_index(axis=1)
         .reset_index())
@jesrael jesrael added Enhancement Needs Triage Issue that has not been reviewed by a pandas team member labels May 19, 2020
@TomAugspurger
Copy link
Contributor

Can you add the code for defining df1?

The request here is for an NDFrame.to_flat_index, with the behavior of

df.index = df.index.to_flat_index()  # or .columns for axis=1

correct?

@TomAugspurger TomAugspurger added API Design and removed Needs Triage Issue that has not been reviewed by a pandas team member labels May 19, 2020
@jesrael
Copy link
Author

jesrael commented May 20, 2020

Yes, something like MultiIndex.droplevel is also implemented Series.droplevel and DataFrame.droplevel

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants