【问题标题】:Filter Dataframe with MultiIndex by specific index value [duplicate]按特定索引值过滤具有 MultiIndex 的数据帧 [重复]
【发布时间】:2020-05-31 16:54:19
【问题描述】:

我每年使用多种场景预测产品的需求。我有一个 MultiIndexed 数据框(模拟、年、月),需要按其中一个进行过滤(比如说模拟)。

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

【问题讨论】:

标签: python pandas multi-index


【解决方案1】:

假设您要索引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

【讨论】:

  • 谢谢!非常清晰和全面。
猜你喜欢
  • 2018-06-19
  • 2018-04-04
  • 2019-04-16
  • 2021-11-21
  • 2015-02-10
  • 1970-01-01
  • 2021-08-23
  • 1970-01-01
相关资源
最近更新 更多