3

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.

RodericDay
  • 1,266
  • 4
  • 20
  • 35
  • What's the transposition function? Is that supposed to work for arbitrary matrices? – Jens Nov 04 '13 at 06:24
  • This is pivot. In [pandas](http://pandas.pydata.org/pandas-docs/stable/reshaping.html), in [numpy](http://stackoverflow.com/questions/17028329/python-create-a-pivot-table) – alko Nov 04 '13 at 06:25
  • I'm still having trouble figuring this one out (just picked pandas up today). Pivot requires an index, but I cannot tell it to keep the current ones (I assume that whichever function did it would ask me what to put on the blanks- 0 vs. NA for example) – RodericDay Nov 04 '13 at 06:47

1 Answers1

4

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
alko
  • 46,136
  • 12
  • 94
  • 102
  • clever, I was trying to find a way to get the name as a column. thanks! – RodericDay Nov 04 '13 at 06:49
  • @alko great, if I just had a bit more practice with pandas :) tried pivot, but didn't want to add index as column and decided that this is not possible to do with pivot – Roman Pekar Nov 04 '13 at 06:52