Reputation: 344
I'm new in pandas and I'm having the following dataframe:
column_A | column_B | |
---|---|---|
row_1 | X1 | Y1 |
row_2 | X2 | Y2 |
and I want to change it in the following format:
column_A_row1 | column_B_row1 | column_A_row2 | column_B_row2 |
---|---|---|---|
X1 | Y1 | X2 | Y2 |
Is there an easy way to do this in pandas (or any other way) ? Thank you!
Upvotes: 0
Views: 32
Reputation: 862611
Use DataFrame.stack
with convert to one row DataFrame by Series.to_frame
and DataFrame.T
, last flatten MultiIndex
:
df = df.stack().to_frame().T
df.columns = df.columns.map(lambda x: f'{x[1]}_{x[0]}')
print (df)
column_A_row_1 column_B_row_1 column_A_row_2 column_B_row_2
0 X1 Y1 X2 Y2
Upvotes: 4