【问题标题】:Groupby with lambda function and multiple columns具有 lambda 函数和多列的 Groupby
【发布时间】:2019-10-22 05:16:34
【问题描述】:

我有一个包含房地产地块销售数据的数据框。我正在尝试按包裹号分组,然后为每个包裹号查看最近的销售和第二次最近的销售,以及这两个日期的相应销售价格。

df = 
parcel  date            amount
101469  5/29/2015 0:00  513000
101469  4/25/2017 0:00  570000
101470  1/6/1995 0:00   75000
101470  8/15/1995 0:00  385000
101470  12/31/2001 0:00 417500


df_grouped = df.groupby("parcel").agg({'date': lambda grp: [grp.nlargest(1).iloc[-1], grp.nlargest(2).iloc[-1]
]})

当前代码正确地按包裹对数据进行分组,并确定最近和第二最近的销售日期。但是,我无法为每个添加相应的销售价格。

这通常是我希望看到的预期结果。一个按每个包裹的行分组,显示最近的销售、第二最近的销售、最近的销售金额、第二最近的销售金额:

【问题讨论】:

  • 请告诉我们您的预期结果。谢谢。
  • 我知道某处有一个 dup
  • 添加了预期结果

标签: python pandas group-by


【解决方案1】:

使用这些步骤:

  • 使用sort_valuesgroupby 创建df1 并选择每组的前2 行
  • 使用cumcountkey 列添加到df1(将其转换为str
  • set_indexunstack 到所需的输出
  • 使用多索引map 将列美化为所需的列名
df1 = df.sort_values('date', ascending=False).groupby('parcel').head(2)
df1['key'] = df1.groupby(['parcel']).parcel.cumcount().add(1).astype(str)
df1 =  df1.set_index(['parcel', 'key']).unstack()
df1.columns = df1.columns.map('_'.join)

Out[1268]:
           date_1     date_2  amount_1  amount_2
parcel
101469 2017-04-25 2015-05-29    570000    513000
101470 2001-12-31 1995-08-15    417500    385000

【讨论】:

    【解决方案2】:

    解决了。原始解决方案在这里:Apply multiple functions to multiple groupby columns

    def f(x):
            d = {}
            d['most_recent_sale'] = x["date"].nlargest(1).iloc[-1]
            d['second_most_recent_sale'] = x["date"].nlargest(2).iloc[-1]
            d['most_recent_price'] = x.loc[x["date"] == d["most_recent_sale"], "amt_Price"].values[0]
            d['second_most_recent_price'] = x.loc[x["date"] == d["second_most_recent_sale"], "amt_Price"].values[0]
    
            return pd.Series(d, index=['most_recent_sale', 'second_most_recent_sale', 'most_recent_price', 'second_most_recent_price'])
    
        df_grouped = df.groupby("id_Pid").apply(f)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-04
      • 1970-01-01
      • 1970-01-01
      • 2019-06-08
      • 2021-02-22
      • 2018-12-31
      • 2015-10-15
      • 1970-01-01
      相关资源
      最近更新 更多