简体   繁体   中英

How do I sort with sort_values() by 2 multiindex columns in Pandas

I'm trying to sort a DataFrame with MultiIndex columns by 2 columns. Can't reach the second column.

Tried passing it as a list of lists but got an error. Tried passing it as a tuple also got an error

sorted_df = df.sort_values(by=([('Measurements','Name')], [('Measurements', 'DateCreated')]), ascending=True, inplace= False)

expected result: data frame sorted by name then by date . Getting key error

Does this work?

sorted_df = df.sort_values(by=[('Measurements','Name'), 
                               ('Measurements', 'DateCreated')], 
                           ascending=True, 
                           inplace= False)

您可能正在寻找groupby功能。

sorted_df = df.groupby(['Name', 'DateCreated'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM