【问题标题】:Pandas dataframe, groupBy aggregate multiple columns and rowsPandas 数据框,groupBy 聚合多列和多行
【发布时间】:2023-03-07 19:31:01
【问题描述】:

我有一个看起来像这样的 pandas DataFrame:

  supply_area transaction_date     price
0       54.98       2006-03-31   48500.0
0       54.98       2006-04-30   48500.0
0       54.98       2006-05-31   48500.0
1       67.28       2006-01-31   54500.0
1       67.28       2006-02-28   54500.0
1       67.28       2006-03-31   54500.0

我想按supply_area 与一个连接transaction_date 和price 的列进行分组,如下所示:

  supply_area transaction_date_price     price
0       54.98       2006-03-31,48500.0,2006-04-30,48500.0,2006-05-31,48500.0
1       67.28       2006-01-31,54500.0,2006-02-28,54500.0,2006-03-31,54500.0

我已经尝试过这个和其他一些东西,但它不起作用。

df = df.groupby('supply_area').agg(
                {'supply_area': 'first', 'transaction_date': ','.join, 'price': ','.join})

我对 python 和 pandas lib 还很陌生,所以我不确定我想要的是否可能。

提前致谢!

【问题讨论】:

    标签: python pandas dataframe pandas-groupby aggregate


    【解决方案1】:

    您可以使用第一个连接创建一个新列(这里称为“joined”,但任何名称都可以),然后连接到 groupby

    df['joined'] = (df['transaction_date'] + ',' + df['price'].astype(str))
    df.groupby('supply_area', as_index=False)['joined'].apply(','.join)
    

    输出:

       supply_area                                              joined
    0        54.98  2006-03-31,48500,2006-04-30,48500,2006-05-31,48500
    1        67.28  2006-01-31,54500,2006-02-28,54500,2006-03-31,54500
    

    【讨论】:

      猜你喜欢
      • 2021-11-01
      • 2020-11-05
      • 2019-10-12
      • 2017-06-07
      • 2017-06-05
      • 2013-02-06
      • 1970-01-01
      • 2017-12-25
      • 2018-07-17
      相关资源
      最近更新 更多