python pandas将数据框展平为列表

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

python pandas flatten a dataframe to a list

pythonlistnumpypandasdataframe

提问by jason

I have a df like so:

我有一个像这样的 df:

import pandas
a=[['1/2/2014', 'a', '6', 'z1'], 
   ['1/2/2014', 'a', '3', 'z1'], 
   ['1/3/2014', 'c', '1', 'x3'],
   ]
df = pandas.DataFrame.from_records(a[1:],columns=a[0])

I want to flatten the df so it is one continuous list like so:

我想展平 df 所以它是一个连续的列表,如下所示:

['1/2/2014', 'a', '6', 'z1', '1/2/2014', 'a', '3', 'z1','1/3/2014', 'c', '1', 'x3']

['1/2/2014', 'a', '6', 'z1', '1/2/2014', 'a', '3', 'z1','1/3/2014', 'c', '1', 'x3']

I can loop through the rows and extendto a list, but is a much easier way to do it?

我可以遍历行和extend列表,但有更简单的方法吗?

采纳答案by Saullo G. P. Castro

You can just use .flatten()on the DataFrame:

您可以只.flatten()在 DataFrame 上使用:

df.values.flatten()

and you can also add .tolist()if you want the result to be a Python list.

.tolist()如果您希望结果为 Python ,您也可以添加list

Edit

编辑

As suggested in the comments, now .to_numpy()is recommended instead of .values.

正如评论中.to_numpy()所建议的那样,推荐使用now而不是.values

回答by Chitrasen

You can try with numpy

你可以试试 numpy

import numpy as np
np.reshape(df.values, (1,df.shape[0]*df.shape[1]))

回答by meloncholy

Maybe use stack?

也许使用堆栈

df.stack().values
array(['1/2/2014', 'a', '3', 'z1', '1/3/2014', 'c', '1', 'x3'], dtype=object)

(Edit:Incidentally, the DF in the Q uses the first row as labels, which is why they're not in the output here.)

编辑:顺便说一句,Q 中的 DF 使用第一行作为标签,这就是为什么它们不在此处的输出中。)