简体   繁体   中英

efficiently flatten multiple columns into a single row in pandas

How can I efficiently "flatten" multiple columns of a dataframe into a single row?

A B
1 'a' 'b'
2 'c' 'd'

To:

A_1 A_2 B_1 B_2
'a' 'c' 'b' 'd'

Create Series with MultiIndex by DataFrame.unstack , convert to DataFrame and transpose, last flatten MultiIndex :

df = df.unstack().to_frame().T
df.columns = df.columns.map(lambda x: f'{x[0]}_{x[1]}')
print (df)
   A_1  A_2  B_1  B_2
0  'a'  'c'  'b'  'd'

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