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
Convert pandas DataFrame into list of lists
提问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 tolist
on the .values
np array:
有一个内置的方法,这将是最快的方法,也叫tolist
上.values
NP阵列:
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_matrix
is deprecated since version 0.23.0
You can use the built in values
or to_numpy
(recommended option) method on the dataframe:
您可以在数据帧上使用内置values
或to_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()