这是 sample data file , 我在 ipython notebook 中执行了以下操作:
!curl -O http://pbpython.com/extras/sales-funnel.xlsx
df = pd.read_excel('./sales-funnel.xlsx')
df['Status'] = df['Status'].astype('category')
df["Status"].cat.set_categories(["won","pending","presented","declined"],inplace=True)
table = pd.pivot_table(df,
index=['Manager', 'Status'],
values=['Price', 'Quantity'],
columns=['Product'],
aggfunc={'Price':[np.sum, np.mean], 'Quantity':len},
fill_value=0
)
这是数据在表
中的样子:
我想选择 (Manager=="Debra Henley") & (Status=="won")
并且它使用 query
方法:
table.query('(Manager=="Debra Henley") & (Status=="won")')
但是如何使用 loc
执行相同的选择?我试过这个但不起作用:
table.loc[['Debra Henley', 'won']]
大家在处理MultiIndex的时候一般用什么?最好的方法是什么?
更新:目前找到两个解决方案:
table.xs(('Debra Henley','won'), level=('Manager', 'Status'))
table.loc[[('Debra Henley', 'won')]]
所以我想在使用 MultiIndex 建立索引时应该使用 tuples
而不是 lists
?
最佳答案
您的规范答案由@ScottBoston 提供。
除了@jezrael 的IndexSlice
方法之外,我将添加它以增加广度和视角。
您也可以使用 pd.DataFrame.xs
截取横截面
table.xs(['Debra Henley', 'won'])
Product
Quantity len CPU 1
Maintenance 0
Monitor 0
Software 0
Price mean CPU 65000
Maintenance 0
Monitor 0
Software 0
sum CPU 65000
Maintenance 0
Monitor 0
Software 0
Name: (Debra Henley, won), dtype: int64
关于python - Pandas 如何对 MultiIndex 进行条件选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43037362/