Python 如何在条件下向pandas中的数据帧添加列名列表

Python 如何在条件下向pandas中的数据帧添加列名列表,python,pandas,list,dataframe,Python,Pandas,List,Dataframe,我有pandas的DataFrame,其中显示了一些单词作为列名。单元格中的值是单词在邮件(行)中的使用次数: 现在我需要一个列表,在每一行的末尾都有单词(列名),但只有在使用单词的情况下。 大概是这样的: +--------+-------+-------+-------+-------+---------------------------+ | index | word1 | word2 | word3 | word4 | text | +---

我有pandas的
DataFrame
,其中显示了一些单词作为列名。单元格中的值是单词在邮件(行)中的使用次数:

现在我需要一个列表,在每一行的末尾都有单词(列名),但只有在使用单词的情况下。 大概是这样的:

+--------+-------+-------+-------+-------+---------------------------+
| index  | word1 | word2 | word3 | word4 |           text            |
+--------+-------+-------+-------+-------+---------------------------+
|      0 |     1 |     2 |     1 |     0 | [word1,word2,word3]       |
|      1 |     2 |     3 |     5 |     1 | [word1,word2,word3,word4] |
|      2 |     0 |     0 |     3 |     0 | [word3]                   |
+--------+-------+-------+-------+-------+---------------------------+

我知道我可以得到一个带有
list(data.columns)
的列表,但我不知道如何设置条件并添加一个包含列表的新列。

请发布您迄今为止尝试的内容以及遇到的问题。
In [136]: df = pd.DataFrame(np.random.randint(0, 3, (3, 5)), columns=list('abcde'))

In [137]: df
Out[137]:
   a  b  c  d  e
0  1  0  1  0  1
1  0  2  0  0  2
2  0  1  1  0  0

In [140]: df['text'] = df.apply(lambda x: df.columns[x.astype(bool)].to_list(), axis=1)

In [141]: df
Out[141]:
   a  b  c  d  e       text
0  1  0  1  0  1  [a, c, e]
1  0  2  0  0  2     [b, e]
2  0  1  1  0  0     [b, c]
In [136]: df = pd.DataFrame(np.random.randint(0, 3, (3, 5)), columns=list('abcde'))

In [137]: df
Out[137]:
   a  b  c  d  e
0  1  0  1  0  1
1  0  2  0  0  2
2  0  1  1  0  0

In [140]: df['text'] = df.apply(lambda x: df.columns[x.astype(bool)].to_list(), axis=1)

In [141]: df
Out[141]:
   a  b  c  d  e       text
0  1  0  1  0  1  [a, c, e]
1  0  2  0  0  2     [b, e]
2  0  1  1  0  0     [b, c]