gpt4 book ai didi

python-3.x - 如何返回某个值第一次出现的每一行的列索引

转载 作者:行者123 更新时间:2023-12-01 01:57:58 24 4
gpt4 key购买 nike

我有一个 pandas 数据框,其中 1 出现在每行的不同列中。一行中第一次出现 1 的列对于不同的行是不同的。我需要创建一个附加列(列索引),其中我想要返回该行中第一次出现 1 的列的索引号。

Example dataframe:

IDs q1 q2 q3 q4 q5 q6 q7 q8

1111 0 0 0 1 0 0 0 1

1122 0 0 1 0 0 1 0 0

the output should like this:

IDs q1 q2 q3 q4 q5 q6 q7 q8 column_index

1111 0 0 0 1 0 0 0 1 5

1122 0 0 1 0 0 1 0 0 4

如果有人可以提供在 pandas 中有用的代码,那将会很有帮助。提前致谢。

最佳答案

您始终可以编写一个简单的函数,然后在数据帧上使用 apply 。

def get_first(row):
for i, col in enumerate(row.index.tolist()):
if row[col] == 1:
return i

df['column_index'] = df.apply(get_first, axis=1)

对于 pandas 来说这可能是一种很酷又棘手的方法,但这确实有效。

如果您不想编写函数,也可以这样做,但它的可读性要差很多

df['first_col'] = df.apply(lambda row: [row.index.tolist().index(c) for c in row.index.tolist() if row[c] == 1][0], axis=1)

关于python-3.x - 如何返回某个值第一次出现的每一行的列索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57260823/

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