[英]How to convert a pandas dataframe multicolumn to one single column
I am trying to convert a pandas dataframe with different columns per year, to a pandas dataframe with one column with the value and other column with the year: I am trying to convert a pandas dataframe with different columns per year, to a pandas dataframe with one column with the value and other column with the year:
input输入
column name: a, b, c, d
column 2015: 1, 2, 3, 4
column 2016: 5, 6, 7, 8
Desired output所需 output
column name: a, b, c, d, a, b, c, d
column year: 2015, 2015, 2015, 2015, 2016, 2016, 2016, 2016
column value: 1, 2, 3, 4, 5, 6, 7, 8
I've trying with a for loop and melt function but is not the ideal solution.我尝试使用 for 循环并融化 function 但不是理想的解决方案。
Thanks!谢谢!
pandas.melt
would do the job. pandas.melt
可以完成这项工作。
print(df)
###
name 2015 2016
0 a 1 5
1 b 2 6
2 c 3 7
3 d 4 8
print(pd.melt(df, value_vars=['2015', '2016'], var_name='year', id_vars='name'))
###
name year value
0 a 2015 1
1 b 2015 2
2 c 2015 3
3 d 2015 4
4 a 2016 5
5 b 2016 6
6 c 2016 7
7 d 2016 8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.