简体   繁体   English

将pandas DataFrame转换为列表列表

[英]Convert pandas DataFrame into list of lists

I have a pandas data frame like this: 我有一个像这样的pandas数据框:

admit   gpa  gre  rank   
0  3.61  380     3  
1  3.67  660     3  
1  3.19  640     4  
0  2.93  520     4

Now I want to get a list of rows in pandas like: 现在我想获得pandas中的行列表,如:

[[0,3.61,380,3], [1,3.67,660,3], [1,3.19,640,4], [0,2.93,520,4]]   

How can I do it? 我该怎么做?

There is a built in method which would be the fastest method also, calling tolist on the .values np array: 有一个内置的方法也是最快的方法,在.values np数组上调用tolist

df.values.tolist()

[[0.0, 3.61, 380.0, 3.0],
 [1.0, 3.67, 660.0, 3.0],
 [1.0, 3.19, 640.0, 4.0],
 [0.0, 2.93, 520.0, 4.0]]

你可以这样做:

map(list, df.values)

EDIT: as_matrix is deprecated since version 0.23.0 编辑: as_matrix自0.23.0版本已经过时

You can use the built in values or to_numpy (recommended option) method on the dataframe: 您可以在数据to_numpy使用内置valuesto_numpy (推荐选项)方法:

In [8]:
df.to_numpy()

Out[8]:
array([[  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.8,   6.1,   5.4, ...,  15.9,  14.4,   8.6],
   ..., 
   [  0.2,   1.3,   2.3, ...,  16.1,  16.1,  10.8],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4]])

If you explicitly want lists and not a numpy array add .tolist() : 如果您明确需要列表而不是numpy数组,请添加.tolist()

df.to_numpy().tolist()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM