I have a dataframe like shown below
Timestamp x_1 x_2 x_3 x_4 x_5 x_6
2018-01-31 22:30:00 2.023844 2.477428 1.023026 1.035433 0.530817 0.576471
2018-02-01 00:00:00 0.198297 -0.012164 0.103245 -0.101643 0.087468 -0.096665
2018-02-01 01:30:00 0.130721 0.042116 0.200378 0.166665 0.263809 0.250849
2018-02-01 03:00:00 0.621256 1.130577 0.907597 1.659503 1.161939 1.966579
2018-02-01 04:30:00 1.399033 2.438298 1.521268 2.570770 1.555749 2.583903
I want to make a new dataframe which consists of only one column like this
vals
2.023844
2.477428
1.023026
1.035433
0.530817
0.576471
0.198297
-0.012164
0.103245
-0.101643
0.087468
-0.096665
0.130721
0.042116
0.200378
0.166665
0.263809
0.250849
I have to take every row values (x_1 to x_6) and stack them into a column.
Is there a easy way to do it in pandas rather than messing around with arrays and lists.?
If first column is not index
:
df = pd.DataFrame({'vals':df.iloc[:, 1:].values.reshape(-1)})
If first column is index:
df = pd.DataFrame({'vals':df.values.reshape(-1)})
print (df)
vals
0 2.023844
1 2.477428
2 1.023026
3 1.035433
4 0.530817
5 0.576471
6 0.198297
7 -0.012164
8 0.103245
9 -0.101643
10 0.087468
11 -0.096665
12 0.130721
13 0.042116
14 0.200378
15 0.166665
16 0.263809
17 0.250849
18 0.621256
19 1.130577
20 0.907597
21 1.659503
22 1.161939
23 1.966579
24 1.399033
25 2.438298
26 1.521268
27 2.570770
28 1.555749
29 2.583903
You can use stack
:
df.iloc[:,1:].stack().to_frame('vals').reset_index(drop=True)
vals
0 2.023844
1 2.477428
2 1.023026
3 1.035433
4 0.530817
5 0.576471
6 0.198297
7 -0.012164
8 0.103245
9 -0.101643
10 0.087468
11 -0.096665
12 0.130721
13 0.042116
14 0.200378
15 0.166665
16 0.263809
17 0.250849
18 0.621256
19 1.130577
20 0.907597
21 1.659503
22 1.161939
23 1.966579
24 1.399033
25 2.438298
26 1.521268
27 2.570770
28 1.555749
29 2.583903
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.