【问题标题】:Retrieve ( index, column ) pair based on value in a row根据行中的值检索(索引,列)对
【发布时间】:2020-03-05 13:51:51
【问题描述】:

我有一个这种格式的数据框

       A    B     C      D

1      a    a     c      c 
2      c    b     a      a 
3      b    a     c      a
.
.
.

我希望使用数据框操作根据行的某个值获取所有(索引、列)对。所有(索引、列、行值)对都是唯一的。

我调查了这个问题:pythonic way to get index,column for value == 1

虽然这与我的问题完全相同,但该问题的公认答案有点模糊,根据这些答案我无法得到我想要的答案。

我也看过类似的:

a)Select specific index, column pairs from pandas dataframe

b)Python Pandas: Get index of rows which column matches certain value

我试过了:

req_cols = df.columns [ ( new_df == "a" ).any() ]

req_inds = (df == "a").index

我能够分别获取索引值和列值,但对如何正确组合它们感到困惑。

如果我选择行值“a”,我希望得到[(1,A), (1,B) , (2,C), (2,D), (3,B), (3,D)]

非常感谢任何帮助。 TIA。

【问题讨论】:

    标签: python pandas indexing


    【解决方案1】:

    wherestack 的一种方式:

    df.where(df.eq('a')).stack().index.values
    

    输出:

    array([(1, 'A'), (1, 'B'), (2, 'C'), (2, 'D'), (3, 'B'), (3, 'D')],
      dtype=object)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-14
      • 2019-11-07
      • 2019-10-08
      • 1970-01-01
      相关资源
      最近更新 更多