python - Pandas::将一列的值作为列

标签 python pandas pivot

数据如下所示:

origin_id   type   serialn     event    year    month    day
1              A       101        X1    2017        6     10
1              A       101        X2    2017        6     10
1              B       101        X3    2017        6     10
2              A       151        X1    2016        7     15
2              B       151        X3    2016        7     15
2              C       151        X4    2016        7     15

我需要这样:

origin_id    serialn   X1    X2    X3   X4    year    month    day
        1        101    A     A     B null    2017        6     10
        2        151    A  null     B    C    2016        7     15

所以基本上我需要的是使用 event 列的值作为标题,并在没有事件时为每个事件放置 type 列的值对于某个 origin_id 放置一个 null。数据帧中的一些其他列,例如 serialnorigin_id 应该位于结果列中。此外,每个 origin_id

应该只有一行

这个问题:How to pivot a dataframe尽管它是为了在某个时刻执行聚合而设计的,但它涉及到了一些要点。

这是一个可能的解决方案。

我得到一个 df,其中 origin_id 作为索引,事件作为列,类型作为它们的值。

stat = df.pivot(values='type', index='origin_id', columns='event')

现在我需要来自原始数据帧的一些信息,因此我只为每个 origin_id 保留一个事件并删除我不会使用的列

df1 = df.drop_duplicates(subset='origin_id').drop(['type','event'], axis=1)

使用 origin_id 的值合并两个数据帧 df1,使用索引合并 stat。

pd.merge(df1, stat, how='inner', left_on = 'origin_id', right_index = True)

使用第一个数据帧和上面的代码我得到这个结果:

origin_id    serialn   X1    X2    X3   X4    year    month    day
        1        101    A     A     B null    2017        6     10
        2        151    A  null     B    C    2016        7     15

还有其他方法可以做到这一点吗?

谢谢!

最佳答案

你可以这样做:

In [85]: df.pivot_table(index=df.columns.drop(['event','type']).tolist(),
                        columns='event',
                        values='type',
                        aggfunc='first') \
            .reset_index()
            .rename_axis(None,1)
Out[85]:
   origin_id  serialn  year  month  day X1    X2 X3    X4
0          1      101  2017      6   10  A     A  B  None
1          2      151  2016      7   15  A  None  B     C

关于python - Pandas::将一列的值作为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48027065/

相关文章:

python - CNN 对猫/狗图像二元分类的准确度并不比随机分类好

python - 对多索引 Pandas 数据框中的行求和

python - pandas 系列的 .ix 索引有什么意义

python - 当对前一个值进行迭代求和时,有没有办法在 pandas 的 apply 函数中使用前一行值?或者是一种有效的方法?

c# - 微妙的 WP7 枢轴 ListViewItem 动画

xaml - 如何隐藏 PivotItem?

Mysql 行连接

python - matplotlib matshow 标签

python - 当作为参数传递时,如何跨多个自定义函数处理 Pandas DataFrame?

python - 使用 SQLAlchemy 连接两个数据库中的表