gpt4 book ai didi

python - 根据行中的值检索(索引,列)对

转载 作者:行者123 更新时间:2023-12-04 15:38:50 25 4
gpt4 key购买 nike

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

       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。

最佳答案

一种方式 wherestack :

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

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

关于python - 根据行中的值检索(索引,列)对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58774883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com