Python 将 Pandas DataFrame 转换为列表列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19585280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:06:45  来源:igfitidea点击:

Convert pandas DataFrame into list of lists

pythonpandasdataframe

提问by user2806761

I have a pandas data frame like this:

我有一个像这样的熊猫数据框:

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:

现在我想获取熊猫中的行列表,例如:

[[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?

我该怎么做?

回答by EdChum

There is a built in method which would be the fastest method also, calling toliston the .valuesnp array:

有一个内置的方法,这将是最快的方法,也叫tolist.valuesNP阵列:

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

回答by Roman Pekar

you can do it like this:

你可以这样做:

map(list, df.values)

回答by Daan

EDIT: as_matrixis deprecated since version 0.23.0

编辑:as_matrix自 0.23.0 版起已弃用

You can use the built in valuesor to_numpy(recommended option) method on the dataframe:

您可以在数据帧上使用内置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()