在pandas的数据框中的每一行中找到非零值的列索引集

Qia*_* Li 7 python pandas

有没有一种很好的方法可以在pandas的数据框中的每一行中找到非零值的列索引集?我是否必须逐行遍历数据框?

例如,数据框是

c1  c2  c3  c4 c5 c6 c7 c8  c9
 1   1   0   0  0  0  0  0   0
 1   0   0   0  0  0  0  0   0
 0   1   0   0  0  0  0  0   0
 1   0   0   0  0  0  0  0   0
 0   1   0   0  0  0  0  0   0
 0   0   0   0  0  0  0  0   0
 0   2   1   1  1  1  1  0   2
 1   5   5   0  0  1  0  4   6
 4   3   0   1  1  1  1  5  10
 3   5   2   4  1  2  2  1   3
 6   4   0   1  0  0  0  0   0
 3   9   1   0  1  0  2  1   0
Run Code Online (Sandbox Code Playgroud)

预计产量将是

['c1','c2']
['c1']
['c2']
...
Run Code Online (Sandbox Code Playgroud)

You*_*Kim 7

看来你必须逐行遍历DataFrame.

cols = df.columns
bt = df.apply(lambda x: x > 0)
bt.apply(lambda x: list(cols[x.values]), axis=1)
Run Code Online (Sandbox Code Playgroud)

你会得到:

0                                 [c1, c2]
1                                     [c1]
2                                     [c2]
3                                     [c1]
4                                     [c2]
5                                       []
6             [c2, c3, c4, c5, c6, c7, c9]
7                 [c1, c2, c3, c6, c8, c9]
8         [c1, c2, c4, c5, c6, c7, c8, c9]
9     [c1, c2, c3, c4, c5, c6, c7, c8, c9]
10                            [c1, c2, c4]
11                [c1, c2, c3, c5, c7, c8]
dtype: object
Run Code Online (Sandbox Code Playgroud)

如果性能很重要,请尝试传递raw=True给布尔数据帧创建,如下所示:

%timeit df.apply(lambda x: x > 0, raw=True).apply(lambda x: list(cols[x.values]), axis=1)
1000 loops, best of 3: 812 µs per loop
Run Code Online (Sandbox Code Playgroud)

它为您带来更好的性能提升.以下是raw=False(默认)结果:

%timeit df.apply(lambda x: x > 0).apply(lambda x: list(cols[x.values]), axis=1)
100 loops, best of 3: 2.59 ms per loop
Run Code Online (Sandbox Code Playgroud)