I have a df like so:
JavaScript
x
7
1
import pandas
2
a=[['1/2/2014', 'a', '6', 'z1'],
3
['1/2/2014', 'a', '3', 'z1'],
4
['1/3/2014', 'c', '1', 'x3'],
5
]
6
df = pandas.DataFrame.from_records(a[1:],columns=a[0])
7
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?
Advertisement
Answer
You can use .flatten()
on the DataFrame converted to a NumPy array:
JavaScript
1
2
1
df.to_numpy().flatten()
2
and you can also add .tolist()
if you want the result to be a Python list
.
Edit
In previous versions of Pandas, the values
attributed was used instead of the .to_numpy()
method, as mentioned in the comments below.