Home > Blockchain >  How can I use row index values as column for dataframe?
How can I use row index values as column for dataframe?

Time:03-06

So, I collected data from 21 participants with 16 EEG channels and I extracted the Gamma band. My current dataframe looks like this ([336 rows x 2 columns]):

Channels Gamma
Fp1 0.345908
Fp2 0.121232
F3 0.213212
..... ....

Now I want to transpose it in such a way, that I have the gamma values for each channel in one column. Like this:

Fp1 Fp2 F3 .... Oz
0.067005 0.345908 0.207540 .... 0.013512
0.137292 0.121232 0.121210 .... 0.121111
0.112121 0.213212 0.123443 .... 0.432233

when I just transpose the dataframe, then I get one row with all channels next to each other:

Fp1 Fp1 Fp1 .... Oz Oz Oz
0.067005 0.345908 0.207540 .... 0.013512 0.12123 0.112423

I looked at pd.melt but I can't figure it out. Can someone help?

Thank you in advance!

CodePudding user response:

One approach is to group by the Channels and then set these groups as columns of your new dataframe. Assuming following dataframe:

  Channels     Gamma
0      Fp1  0.345908
1      Fp2  0.121232
2      Fp1  0.455908
3      Fp2  0.213212

Then apply this code to the dataframe:

pd.concat(
        {k: g.reset_index(drop=True) 
            for k, g in df.groupby('Channels')['Gamma']}, axis=1)

and receive the following output:

        Fp1       Fp2
0  0.345908  0.121232
1  0.455908  0.213212
  • Related