简体   繁体   English

使用 Pandas NamedAgg 按多列分组和聚合

[英]Group and aggregate by multiple columns using Pandas NamedAgg

I have a dataframe that has columns arranged by date.我有一个按日期排列的列的数据框。 The columns are readings taken every day for over a year.这些列是一年多以来每天读取的读数。 I am trying to aggregate and group this data to show quarterly aggregated numbers.我正在尝试汇总和分组这些数据以显示季度汇总数字。 I found pandas namedagg to possible support this, but I am struggling to pass multiple column names and apply a single aggregate function.我发现大熊猫 namedagg 可能支持这一点,但我正在努力传递多个列名并应用单个聚合函数。

My sample dataset, showing city, zip and rest of columns arranged by date every day between 2020 to 2021我的示例数据集,显示了 2020 年到 2021 年之间每天按日期排列的城市、邮编和其余列

在此处输入图片说明

Here is what I am trying to achieve, and given below is an example of what I tried by passing multiple columns to the NamedAgg method, but it doesn't seem to accept it:这是我想要实现的目标,下面给出了我通过将多列传递给 NamedAgg 方法所尝试的示例,但它似乎不接受它:

df.groupby(['city','zip']).agg(
  2021_q1=pd.NamedAgg(column=df.columns[1:89].values.tolist(),aggfunc=sum),
  2021_q2=pd.NamedAgg(column=df.columns[90:180].values.tolist(),aggfunc=sum),
  2021_q3=pd.NamedAgg(column=df.columns[181:240].values.tolist(),aggfunc=sum),
  2021_q4=pd.NamedAgg(column=df.columns[241:380].values.tolist(),aggfunc=sum),
  2022_q1=pd.NamedAgg(column=df.columns[381:450].values.tolist(),aggfunc=sum),
)

I get the error我收到错误

TypeError: unhashable type: 'list'类型错误:不可散列的类型:“列表”

Is there another way I should be passing the list of columns I want to aggregate or please suggest if there is better way of aggregating my dataset by quarterly numbers是否有另一种方式我应该传递我想要聚合的列列表,或者请建议是否有更好的方法来按季度数字聚合我的数据集

Convert non dates columns to index, convert columns to datetimes and then aggregate values converted to quarter periods by DatetimeIndex.to_period :将非日期列转换为索引,将列转换为日期时间,然后通过DatetimeIndex.to_period聚合转换为季度周期的值:

df = df.set_index(['city','zip'])

df.columns = pd.to_datetime(df.columns)

df1 = df.groupby(df.columns.to_period('Q'), axis=1).sum()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM