RodericDay
RodericDay

Reputation: 1292

Trying to do a strange tranpose with Python pandas

I want to turn this DataFrame

                x           K
methane  0.006233  109.237632
ethane   0.110002    6.189667
propane  0.883765    0.770425

into something like this

           0.006233    0.110002    0.883765
methane  109.237632           -           -
ethane            -    6.189667           -
propane           -           -    0.770425

I keep hesitating on whether this is a regular thing to do and digging through the docs or whether I should code something myself. I don't know what I would call this operation.

Upvotes: 3

Views: 89

Answers (1)

alko
alko

Reputation: 48347

Thanks @RomanPekar for test case, you can pivot with:

>>> df = pd.DataFrame({'x':[0.006233,0.110002,0.883765], 'K':[109.237632,6.189667,0.770425]}, index=['methane','ethane','propane'])
>>> df['name'] = df.index
>>> df.pivot(index='name', columns='x', values='K')
x          0.006233  0.110002  0.883765
name
ethane          NaN  6.189667       NaN
methane  109.237632       NaN       NaN
propane         NaN       NaN  0.770425

Upvotes: 4

Related Questions