I have a dataset with the following structure, with varying sizes.:
A B C D E F G H I J
1 8 7 1 3 4 7 1 5 9
8 9 1 4 7 4 5 2 1 2
8 9 7 7 4 2 9 7 1 0
What I want to do is append all columns to the first column and achieve a result like this:
A
1
8
8
8
9
9
7
1
7
1
7
...
My code so far: import pandas as pd
df = pd.read_csv("data.csv", header=None, delimiter=";")
for column in df:
df.append(column)
print(df)
I figured it should work by looping over all columns and using .append to append them to the first column.
Any help is appreciated
I believe here is better use numpy
, solution with numpy.ravel
with transpose numpy array:
df = pd.DataFrame({'A':df.values.T.ravel()})
print (df)
A
0 1
1 8
2 8
3 8
4 9
5 9
6 7
7 1
8 7
9 1
10 4
11 7
12 3
13 7
14 4
15 4
16 4
17 2
18 7
19 5
20 9
21 1
22 2
23 7
24 5
25 1
26 1
27 9
28 2
29 0
您可以使用reshape
执行以下操作:
df = pd.DataFrame(df.values.reshape(-1), columns=['A'])
Maybe using melt
df.melt()
Out[72]:
variable value
0 A 1
1 A 8
2 A 8
3 B 8
4 B 9
5 B 9
6 C 7
7 C 1
8 C 7
9 D 1
10 D 4
11 D 7
12 E 3
13 E 7
14 E 4
15 F 4
16 F 4
17 F 2
18 G 7
19 G 5
20 G 9
21 H 1
22 H 2
23 H 7
24 I 5
25 I 1
26 I 1
27 J 9
28 J 2
29 J 0
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.