python - 获取行中条件匹配的列名

标签 python python-3.x pandas dataframe

我有一个 pandas 数据框,如下所示:

        A     B     C     D     E     F     G     H     I
1       0.0   1.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0
2       1.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0
3       0.0   1.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0

现在,对于每个,我必须检查哪个包含1,然后将此列名称记录在新列中。最终的数据框将如下所示:

        A     B     C     D     E     F     G     H     I     IsTrue
1       0.0   1.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   B
2       1.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   A
3       0.0   1.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   B

有没有更快且pythonic的方法来做到这一点?

最佳答案

这是使用 DataFrame.dot 的一种方法:

df['isTrue'] = df.astype(bool).dot(df.columns)

    A    B    C    D    E    F    G    H    I    isTrue
1  0.0  1.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0      B
2  1.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0      A
3  0.0  1.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0      B

为了获得更好的性能,您可以使用:

df['isTrue'] = df.columns[df.to_numpy().argmax(1)]

关于python - 获取行中条件匹配的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56101061/

相关文章:

python - Azure CosmosDB 为什么在插入 Azure CosmosDB 时不自动添加 'id' 字段?

python - 如何在 Python 中导入子模块? (没有 `exec` )

python - 基于列值 reshape Pandas 数据框

python - 排除小于 0 的值失败

python - 用新实例替换类的实例

python - TimeDistributed 与 TimeDistributedDense Keras

django - 在 Django 中,如何防止 "Save with update_fields did not affect any rows."错误?

Python 计算数据透视表中的所有 bool 值

python - 使用 Map 并行化 for 循环并使用 pyspark 在 Spark 中减少

python - 寻找最大公约数(作业打错了,我迫切需要你的帮助)