Home > OS >  Pandas - pivot dataframe turning classes into column names
Pandas - pivot dataframe turning classes into column names

Time:04-21

I have a df, with a column for labels and another for all its samples:

    network k
0       c1  25.0
1       c1  30.0
3       z_7 11.0
4       z_7 13.0

How do I transpose it, turning each label into a column name, with its samples as column values, like so:

    c1    z_7
0   25.0  11.0
1   30.0  13.0

CodePudding user response:

df = pd.pivot(df, columns='network', values='k')
c1 = df['c1'].dropna().reset_index(drop=True)
z_7 = df['z_7'].dropna().reset_index(drop=True)
print(pd.concat([c1, z_7], axis=1))

Output:

     c1   z_7
0  25.0  11.0
1  30.0  13.0
  • Related