简体   繁体   中英

How to unpivot columns with same name?

Consider a dataframe,

    A   A   B   B                            

0 1 4 7 10
1 2 5 8 11
2 3 6 9 12

I want to append all columns with the same name. For eg:

   A    B  

0 1 7
1 2 8
2 3 9
0 4 10
1 5 11
2 6 12

You can create MultiIndex in columns and then reshape by stack :

s = df.columns.to_series()
df.columns = [df.columns, s.groupby(s).cumcount()]
print (df)
   A     B    
   0  1  0   1
0  1  4  7  10
1  2  5  8  11
2  3  6  9  12

df = df.stack().sort_index(level=1).reset_index(drop=True)
print (df)
   A   B
0  1   7
1  2   8
2  3   9
3  4  10
4  5  11
5  6  12

You could

In [319]: pd.concat(x for _, x in df.groupby(df.columns.duplicated(), axis=1))
Out[319]:
   A   B
0  1   7
1  2   8
2  3   9
0  4  10
1  5  11
2  6  12

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