按特定索引值筛选具有多索引的数据帧



我每年使用许多场景来预测产品的需求。我有一个多索引数据帧(模拟、年、月(,需要按其中一个进行过滤(假设模拟(。

import pandas as pd
idx = pd.MultiIndex.from_tuples([(1,2020,1), (1,2020,2), (2,2020,1), (2,2020,2)], 
names=['Simulation', 'Year', 'Month'])
d = {'Apples': [1,2,3,4], 'Organes': [4,5,6,8], 'Lemons': [9,10,11,12]}
df = pd.DataFrame(d, index=idx)
print(df)
Simulation   Year    Month     Apples  Oranges  Lemons
1            2020    1         1       4        9
1                    2         2       5        10
2            2020    1         3       6        11
2                    2         4       8        12

如何按模拟进行筛选?

仅按模拟编号 1 过滤的预期输出

Simulation   Year    Month     Apples  Oranges  Lemons
1            2020    1         1       4        9
1                    2         2       5        10

假设你想在Simulation为1的位置建立索引,你可以使用index.get_level_values作为:

df[df.index.get_level_values(0) == 1]
Apples  Oranges  Lemons
Simulation Year Month                         
1          2020 1          10       30      10
2          25       50       5
2030 12         30       70       5

对于多个值,可以在末尾为列表中的值添加isin

df.loc[df.index.get_level_values(0).isin([1, 2])]

Apples  Oranges  Lemons
Simulation Year Month                         
1          2020 1          10       30      10
2          25       50       5
2030 12         30       70       5
2          2020 1          15       25      10
2          20       50      15

get_level_values基本上返回一个包含沿第一个轴的所有索引的Int64Index

df.index.get_level_values(0)
# Int64Index([1, 1, 1, 2, 2, 50], dtype='int64', name='Simulation') 

然后,我们可以使用该结果沿感兴趣轴对数据帧执行布尔索引。


或者您也可以使用pd.IndexSlice

df.loc[pd.IndexSlice[[1,2], :, :]]
Apples  Oranges  Lemons
Simulation Year Month                         
1          2020 1          10       30      10
2          25       50       5
2030 12         30       70       5
2          2020 1          15       25      10
2          20       50      15

最新更新