我有这种格式的数据框
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。
答案 0 :(得分:1)
使用where
和stack
的一种方式:
df.where(df.eq('a')).stack().index.values
输出:
array([(1, 'A'), (1, 'B'), (2, 'C'), (2, 'D'), (3, 'B'), (3, 'D')],
dtype=object)