pandas 列值到列? [英] Pandas column values to columns?

查看:83
本文介绍了 pandas 列值到列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了将一个列/系列分解为Pandas数据框的多个列的主题的几种变体,但是我一直在尝试做点事情,而实际上并没有成功地使用现有方法.

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 succeeding with the existing approaches.

给出如下所示的DataFrame:

Given a DataFrame like so:

    key       val
id
2   foo   oranges
2   bar   bananas
2   baz    apples
3   foo    grapes
3   bar     kiwis

我想将key系列中的项目转换为以val值作为值的列,例如:

I want to convert the items in the key series into columns, with the val values serving as the values, like so:

        foo        bar        baz
id
2   oranges    bananas     apples
3    grapes      kiwis        NaN

我觉得这应该是相对简单的事情,但是随着卷积水平的提高,我已经为此花了几个小时不停地努力.

I feel like this is something that should be relatively straightforward, but I've been bashing my head against this for a few hours now with increasing levels of convolution, and no success.

推荐答案

有几种方法:

使用 .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

使用 .pivot :

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

使用 .groupby ,后跟 .unstack :

>>> df.reset_index().groupby(['id', 'key'])['val'].aggregate('first').unstack()
key      bar     baz      foo
id                           
2    bananas  apples  oranges
3      kiwis     NaN   grapes

这篇关于 pandas 列值到列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆