Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading