【问题标题】:Using only .loc[], how can you extract a single index-column in a multi-indexed df?仅使用 .loc[],如何在多索引 df 中提取单个索引列?
【发布时间】:2022-10-07 10:22:33
【问题描述】:

我知道有很多关于从多索引 df 中提取单个索引列的一般主题的帖子。我希望可以区分这个问题,因为我还没有找到回答这个狭窄点的东西。

但基本上,假设我有一个多索引 df, test2

test = pd.DataFrame({\'credit_score\': [608, 607, 502, 699, 850], \'age\': [42, 41, 42, 39, 43], \'exited\': [\'Yes\', \'No\', \'Yes\', \'No\', \'No\'], \'surname\': [\'Hargrave\', \'Hill\', \'Hill\', \'Boni\', \'Mitchell\'], \'geography\': [\'France\', \'Spain\', \'France\', \'France\', \'Spain\']})
test2 = test.set_index([\'credit_score\', \'age\'])

如果我想通过 .loc 从 test2 (\'age\') 中提取单个索引列,即使用只要test2.loc[fill_in_code],我该怎么做?

我知道替代方法,如 .query()、.get_level_values() 等,但我试图更好地了解 .loc 本身的通用性。解释或解释的链接表示赞赏。

    标签: python pandas dataframe subset pandas-loc


    【解决方案1】:

    检查pd.IndexSlice

    test2.loc[pd.IndexSlice[:,42],:]
    

    https://pandas.pydata.org/docs/user_guide/advanced.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-06
      • 2023-03-27
      • 2013-11-05
      • 2020-10-31
      • 2020-03-07
      • 2018-07-27
      • 1970-01-01
      • 2017-01-10
      相关资源
      最近更新 更多