将pandas数据框转换为列表 [英] Convert pandas dataframe to a list

查看:117
本文介绍了将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

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

I would like to convert this to the following:

[['apple', 'banana', 'carrot'],
 ['banana'],
 ['apple'],
 ['apple', 'carrot', 'diet coke'],
 ['banana', 'carrot'],
 ['banana', 'carrot']]

我该怎么办?非常感谢.

How can I do it? Thanks a lot.

推荐答案

由于寿命短,我可能会做些简单的事情

Because life is short, I might do something straightforward like

>>> 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']]

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

This works because we can use a boolean array (row.astype(bool)) to select only the elements of df.columns where the row has True.

这篇关于将pandas数据框转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆