简体   繁体   中英

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:

input

column name: a, b, c, d
column 2015: 1, 2, 3, 4
column 2016: 5, 6, 7, 8

Desired 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.

Thanks!

pandas.melt would do the job.

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

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.

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