简体   繁体   中英

How to merge multiple columns into 1 indicator by using Pandas?

I have the data set:

Class   2000    2001    2002    2003
A   1   2   3   4
B   5   5   4   4
C   2   1   5   6

And I want to have the result like this:

Class   Year    Value
A   2000    1
A   2001    2
A   2002    3
A   2003    4
B   2000    5
B   2001    5
B   2002    4
B   2003    4
C   2000    2
C   2001    1
C   2002    5
C   2003    6

Please help me!

You are looking to un-pivot the DataFrame, in Pandas they call it 'pandas.melt' [link]

For your example:

pandas.melt(df, id_vars=['Class'], value_vars=['2000','2001','2002','2003'])

You can use pd.melt along with sort_values() .

Since doing sort_values() jumbles up the index, you reset_index and then rename the column

import pandas as pd
from io import StringIO

d = '''Class   2000    2001    2002    2003
A   1   2   3   4
B   5   5   4   4
C   2   1   5   6'''

df = pd.read_csv(StringIO(d), sep='\s+')

df2 = pd.melt(df, id_vars=['Class'], value_vars=['2000','2001','2002','2003']).sort_values(by=['Class'])
df2 = df2.reset_index(drop=True)

df2 = df2.rename(columns={'variable':'Year'})
print(df2)

# output
  Class  Year  value
0      A  2000      1
1      A  2001      2
2      A  2002      3
3      A  2003      4
4      B  2000      5
5      B  2001      5
6      B  2002      4
7      B  2003      4
8      C  2000      2
9      C  2001      1
10     C  2002      5
11     C  2003      6

Link for doing check online: Online Check

I created it in a method chain with a pandas feature.

df = df.set_index('Class').unstack().reset_index().rename(columns={'level_0':'Year', 0:'Value'}).sort_values(['Class','Year']).reset_index(drop=True)

df
Year    Class   Value
0   2000    A   1
1   2001    A   2
2   2002    A   3
3   2003    A   4
4   2000    B   5
5   2001    B   5
6   2002    B   4
7   2003    B   4
8   2000    C   2
9   2001    C   1
10  2002    C   5
11  2003    C   6

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