简体   繁体   English

使用pandas将列追加到列

[英]Appending columns to a column using pandas

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 到目前为止,我的代码:将pandas导入为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. 我认为它应该通过遍历所有列并使用.append将它们附加到第一列来工作。

Any help is appreciated 任何帮助表示赞赏

I believe here is better use numpy , solution with numpy.ravel with transpose numpy array: 我相信这里最好使用numpy ,解决方案numpy.ravel与转置numpy数组:

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 也许使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM