将pandas数据帧转换为列表

kev*_*vin 5 python pandas

我有一个pandas数据帧:

apple   banana  carrot  diet coke
1         1       1         0
0         1       0         0
1         0       0         0
1         0       1         1
0         1       1         0
0         1       1         0
Run Code Online (Sandbox Code Playgroud)

我想将此转换为以下内容:

[['apple', 'banana', 'carrot'],
 ['banana'],
 ['apple'],
 ['apple', 'carrot', 'diet coke'],
 ['banana', 'carrot'],
 ['banana', 'carrot']]
Run Code Online (Sandbox Code Playgroud)

我该怎么做?非常感谢.

DSM*_*DSM 6

因为生命很短暂,我可能会做一些直截了当的事情

>>> fruit = [df.columns[row.astype(bool)].tolist() for row in df.values]
>>> pprint.pprint(fruit)
[['apple', 'banana', 'carrot'],
 ['banana'],
 ['apple'],
 ['apple', 'carrot', 'diet coke'],
 ['banana', 'carrot'],
 ['banana', 'carrot']]
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为我们可以使用布尔数组(row.astype(bool))来仅选择df.columns行具有True 的元素.