Python 将数据帧转换为列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35318700/
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 16:16:45  来源:igfitidea点击:

Convert dataFrame to list

pythonpandasdataframe

提问by Pau Folch Codera

I have a pandas dataframe that I convert to numpy array as follows:

我有一个 Pandas 数据框,我将其转换为 numpy 数组,如下所示:

df.values

which gives the following output:

这给出了以下输出:

array([[2],
       [0],
       [1],
       ..., 
       [0],
       [1],
       [0]], dtype=int64)

However I want to obtain the list as follows:

但是我想获得如下列表:

[0, 2, 3]

Any idea how to do this?

知道如何做到这一点吗?

采纳答案by jezrael

Maybe you can use ilocor locfor selecting column and then tolist:

也许您可以使用ilocloc选择列,然后tolist

print df
   a
0  2
1  0
2  1
3  0
4  1
5  0

print df.values
[[2]
 [0]
 [1]
 [0]
 [1]
 [0]]

print df.iloc[:, 0].tolist()
[2, 0, 1, 0, 1, 0]

Or maybe:

或者可能:

print df.values.tolist()
[[2L], [0L], [1L], [0L], [1L], [0L]]

print df.iloc[:, 0].values.tolist()
[2L, 0L, 1L, 0L, 1L, 0L]

print df.loc[:, 'a'].tolist()
[2, 0, 1, 0, 1, 0]

print df['a'].tolist()
[2, 0, 1, 0, 1, 0]

But maybe you need flatten:

但也许你需要flatten

print df.values.flatten()
[2 0 1 0 1 0]

print df.iloc[:, 0].values.flatten()
[2 0 1 0 1 0]

回答by OkezieE

Looks like you have a dataframe with one column and several rows. Remember that this is a two dimensional array, you have to slice the first column then list the values within that column.

看起来您有一个包含一列多行的数据框。请记住,这是一个二维数组,您必须对第一列进行切片,然后列出该列中的值。

This should do it:

这应该这样做:

df[0].values.tolist()

df[0]- This selects all values in the first column. For the second column you'd use df[1]third df[2]and so on.

df[0]- 这将选择第一列中的所有值。对于第二列,您将使用df[1]第三列df[2],依此类推。

You can tell the shape of your dataframe by running df.shape. This will tell you how many rows and columns exist in your dataframe e.g. (9,1)which means 9 rows and 1 column

您可以通过运行来判断数据框的形状df.shape。这将告诉您数据框中存在多少行和列,例如(9,1),这意味着 9 行和 1 列