【问题标题】:Get the row and column labels for selected values in a Pandas dataframe获取 Pandas 数据框中选定值的行和列标签
【发布时间】:2016-10-28 18:11:21
【问题描述】:

我想获取匹配数据框中某些条件的值的行和列标签。为了保持有趣,我需要它与分层(多)索引一起使用。例如:

df = pd.DataFrame(np.arange(16).reshape(4, 4), columns=pd.MultiIndex.from_product((('a', 'b'), ('x', 'y'))))

    a       b    
    x   y   x   y
0   0   1   2   3
1   4   5   6   7
2   8   9  10  11
3  12  13  14  15

现在假设我想要元素的行和列标签

df % 6 == 0

       a             b       
       x      y      x      y
0   True  False  False  False
1  False  False   True  False
2  False  False  False  False
3   True  False  False  False

我想得到

[(0, ('a', 'x')), (1, ('b', 'x')), (3, ('a', 'x'))]

请注意,我想要一个通用解决方案,它不依赖于单调的索引或我的示例中的特定选择。这个问题已经被问过很多次了,但答案并不笼统:

Pandas 真的这么难吗?

【问题讨论】:

    标签: python pandas indexing


    【解决方案1】:

    使用np.where 获取 True 值的序数索引:

    import numpy as np
    import pandas as pd
    df = pd.DataFrame(np.arange(16).reshape(4, 4), 
                      columns=pd.MultiIndex.from_product((('a', 'b'), ('x', 'y'))))
    
    mask = (df % 6 == 0)
    i, j = np.where(mask)
    print(list(zip(df.index[i], df.columns[j])))
    

    产量

    [(0, ('a', 'x')), (1, ('b', 'x')), (3, ('a', 'x'))]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-05
      • 2023-03-03
      • 2020-12-07
      • 2018-02-03
      • 2023-02-07
      • 2018-12-25
      • 1970-01-01
      相关资源
      最近更新 更多