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
python pandas flatten a dataframe to a list
提问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]))

