Reputation: 95
How do I go from a data frame:
df = pd.DataFrame({'a': range(0, 10), 'b': range(10, 20), 'c': range(20, 30)})
that looks like:
a b c
0 0 10 20
1 1 11 21
2 2 12 22
3 3 13 23
4 4 14 24
5 5 15 25
6 6 16 26
7 7 17 27
8 8 18 28
9 9 19 29
and convert it into a list: ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29']
Upvotes: 1
Views: 59
Reputation: 496
Using numpy:
list(np.reshape(df.values, -1, order='F'))
Your df has a shape of (10,3), and you want a shape of (30,). You can achieve this with numpy's reshape.
-1
is simply a shortcut for (30,)
in this instance.
order='F'
ensures that you get values "column-wise," as was presented in your desired output.
Using NumPy methods via tolist
, you can use:
df.values.reshape(-1, order='F').tolist()
Upvotes: 3
Reputation: 1771
I imagine there is probably a better way, but the following will work:
import pandas as pd
df = pd.DataFrame({'a': range(0, 10), 'b': range(10, 20), 'c': range(20, 30)})
mylist = list()
for i in df.columns:
mylist += map(str, df[i].values.tolist())
print(mylist)
Output:
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29']
Upvotes: 1