Question :
python pandas flatten a dataframe to a list
I have a df like so:
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:
['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 extend
to a list, but is a much easier way to do it?
Answer #1:
You can just use .flatten()
on the DataFrame:
df.values.flatten()
and you can also add .tolist()
if you want the result to be a Python list
.
Edit
As suggested in the comments, now .to_numpy()
is recommended instead of .values
.
Answer #2:
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.)
Answer #3:
You can try with numpy
import numpy as np
np.reshape(df.values, (1,df.shape[0]*df.shape[1]))