简体   繁体   English

如何在excel / python中将多行转换为堆叠列?

[英]How to convert multiple rows into stacked columns in excel /python?

Is there an easy way to convert from Type A to Type B. 有没有一种简单的方法可以将类型A转换为类型B。

请参阅图像链接

Note : Kutools (Plugin in Excel) provides a solution for it but that is not robust and does not seem scalable. 注意:Kutools(Excel中的插件)为此提供了一个解决方案,但它不可靠且似乎不可扩展。

Any workaround for this ? 任何解决方法?

Considering you can make the df look like below : (just remove the top row which says Type A ) 考虑到您可以使df如下所示:(只需删除表示Type A的第一行)

    GDP per capita      1950    1951    1952    1953
0   Antigua and Barbuda 3544    3633    3723    3817
1   Argentina           7540    7612    7019    7198
2   Armenia             1862    1834    1914    1958
3   Aruba               3897    3994    4094    4196
4   Australia           12073   12229   12084   12228
5   Austria             6919    7382    7386    7692

Using pd.melt() 使用pd.melt()

>>pd.melt(df,id_vars='GDP per capita',var_name='Year',value_name='GDP Value')

    GDP per capita      Year    GDP Value
0   Antigua and Barbuda 1950    3544
1   Argentina           1950    7540
2   Armenia             1950    1862
3   Aruba               1950    3897
4   Australia           1950    12073
5   Austria             1950    6919
6   Antigua and Barbuda 1951    3633
7   Argentina           1951    7612
8   Armenia             1951    1834
9   Aruba               1951    3994
10  Australia           1951    12229
11  Austria             1951    7382
12  Antigua and Barbuda 1952    3723
13  Argentina           1952    7019
14  Armenia             1952    1914
15  Aruba               1952    4094
16  Australia           1952    12084
17  Austria             1952    7386
18  Antigua and Barbuda 1953    3817
19  Argentina           1953    7198
20  Armenia             1953    1958
21  Aruba               1953    4196
22  Australia           1953    12228
23  Austria             1953    7692

To get the exact look like the image you have posted use: 要获得与您发布的图像完全相同的外观,请使用:

df1=pd.melt(df,id_vars='GDP per capita',var_name='Year',value_name='GDP Value')
df1.rename(columns={'GDP per capita':'Country'},inplace=True)
df1['GDP'] = 'GDP per capita'
df1 = df1[['GDP','Country','Year','GDP Value']]
df1.to_csv('filepath+filename.csv,index=False)

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

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