【问题标题】:Groupby columns on ID and month and assign value for each month as new colmunsID 和月份上的 Groupby 列,并将每个月的值分配为新列
【发布时间】:2020-05-17 18:14:08
【问题描述】:

我有一个数据集,其中我按具有相同 id 的每月数据分组:

temp1 = listvar[2].groupby(["id", "month"])["value"].mean()

这会导致:

id       month

SN10380  1       -9.670370
         2       -8.303571
         3       -4.932143
         4        0.475862
         5        5.732000
                    ...   
SN99950  8        6.326786
         9        4.623529
         10       1.290566
         11      -0.867273
         12      -2.485455

然后我希望每个月和相应的值作为同一 ID 上的一个自己的列,如下所示:

  id         month_1     month_2  month_3   month_4 .... month_12

  SN10380   -9.670370   -8.303571 .....

  SN99950

我使用 apply()、transform() 和 agg() 尝试了不同的解决方案,但无法产生想要的输出。

【问题讨论】:

  • 试试pivot
  • @sammywemmy 谢谢,工作就像一个魅力!多么简单的解决方案!

标签: python pandas dataframe


【解决方案1】:

您可以使用unstack。这是示例代码:

import pandas as pd

df = pd.DataFrame({
    "id": [1, 1, 1, 1, 1, 2, 2, 2, 2, 2],
    "month": [1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
    "value": [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
})

temp1 = df.groupby(["id", "month"])["value"].mean()

temp1.unstack()

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 2021-12-29
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多