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

2024-04-16 04:15:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: 数据importpandasdf产品as场景year
1条回答
网友
1楼 · 发布于 2024-04-16 04:15:33

假设要在Simulation为1的位置建立索引,可以使用^{}作为:

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

对于多个值,可以在列表中的值的末尾添加^{}

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') 

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


或者也可以使用^{}

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

相关问题 更多 >