Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a dataframe with multiple rows into one row using pandas?

Having the following dataframe,

      0      1      2
A    0.2    0.4    0.6
B    0.1    0.1    0.3

How to achieve this transformation, while merging the row index with column name?

     A_0    A_1    A_2    B_0    B_1    B_2
0    0.2    0.4    0.6    0.1    0.1    0.3
like image 844
Avis Avatar asked May 05 '16 17:05

Avis


1 Answers

Use stack followed by a transpose to get the DataFrame in the right shape, then format the column names as appropriate.

df = df.stack().to_frame().T
df.columns = ['{}_{}'.format(*c) for c in df.columns]
like image 85
root Avatar answered Oct 25 '22 14:10

root