熊猫DF。对于每一行,返回 True 值的列名

时间:2021-06-29 03:12:57

标签: python pandas dataframe

我有一个多行、5k+ 和大约 10 列 True/False 的 Pandas df。在每一行中,只有一个列的条目为真,其余 9 个为假。

# Import library
import pandas as pd

# Create dictionary and convert to pd DF
test = {"col1":[True, False, True, True, False],
        "col2":[False, True, False, False, True]}

test = pd.DataFrame(test)

# Show case a dataframe
print(test)

数据框应该看起来像

    col1    col2
0   True    False
1   False   True
2   True    False
3   True    False
4   False   True|

我希望返回具有以下值的数组:

output_array = ['col1','col2','col1','col1','col2']

我被卡住了,我知道我可能应该使用某种应用方法并索引 10 列,但我不确定筛选一行元素的子集为 True 并返回该列的最佳方法。非常感谢您的任何帮助!

1 个答案:

答案 0 :(得分:2)

true_col_name = test.idxmax(axis=1)

会给你一个列名具有 True 值的系列,假设实际上每行只有一个 True 值。

In [6]: test.idxmax(axis=1)
Out[6]: 
0    col1
1    col2
2    col1
3    col1
4    col2
dtype: object