简体   繁体   中英

pandas multiindex index slice range

How can I subselect a pandas multi index easily for a range of values?

import pandas as pd
mini_df = pd.DataFrame({'foo':[1,2,3,4,5,6,7,8,9]})
mini_df['value'] = 2
mini_df['bar'] = 1
mini_df = mini_df.set_index(['bar', 'foo']).unstack()
mini_df['thing'] = -1
display(mini_df.head())

This:

mini_df[['thing', ('value', 2:5)]]

obviously fails to work.

Ie how could I get an index slice that holds the column thing and the value columns 6-9?

在此处输入图像描述

This gives the index slice that holds the column thing and the value columns 6-9:

mini_df.loc[:, ('value', 6): ('thing', '')]

    value          thing
foo     6  7  8  9
bar
1       2  2  2  2    -1

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