Pandas column values to columns?

后端 未结 2 1273
旧时难觅i
旧时难觅i 2020-12-04 07:38

I\'ve seen a few variations on the theme of exploding a column/series into multiple columns of a Pandas dataframe, but I\'ve been trying to do something and not really succe

相关标签:
2条回答
  • 2020-12-04 08:04

    There are a few ways:

    using .pivot_table:

    >>> df.pivot_table(values='val', index=df.index, columns='key', aggfunc='first')
    key      bar     baz      foo
    id                           
    2    bananas  apples  oranges
    3      kiwis     NaN   grapes
    

    using .pivot:

    >>> df.pivot(index=df.index, columns='key')['val']
    key      bar     baz      foo
    id                           
    2    bananas  apples  oranges
    3      kiwis     NaN   grapes
    

    using .groupby followed by .unstack:

    >>> df.reset_index().groupby(['id', 'key'])['val'].aggregate('first').unstack()
    key      bar     baz      foo
    id                           
    2    bananas  apples  oranges
    3      kiwis     NaN   grapes
    
    0 讨论(0)
  • 2020-12-04 08:25

    You could use set_index and unstack

    In [1923]: df.set_index([df.index, 'key'])['val'].unstack()
    Out[1923]:
    key      bar     baz      foo
    id
    2    bananas  apples  oranges
    3      kiwis    None   grapes
    

    Or, a simplified groupby

    In [1926]: df.groupby([df.index, 'key'])['val'].first().unstack()
    Out[1926]:
    key      bar     baz      foo
    id
    2    bananas  apples  oranges
    3      kiwis    None   grapes
    
    0 讨论(0)
提交回复
热议问题