【问题标题】:Groupby and apply a specific function to certain columns and get first or last values of the df PandasGroupby 并将特定函数应用于某些列并获取 df Pandas 的第一个或最后一个值
【发布时间】:2021-11-20 16:39:47
【问题描述】:

基于之前的帖子:Groupby and apply a specific function to certain columns and another function to the rest of the df Pandas

我想对具有大量列的数据框进行分组,但仅将函数(sum、mean 等)应用于两列并获取剩余列的第一个值。我怎样才能做到这一点?在引用的帖子中,以下代码有效,但是当我将“esle x.mean()”替换为“esle x.first()”时,它不再起作用了。

df = df.groupby('id').agg(lambda x : x.count() if x.name in ['var1','var2'] else x.mean())

有什么想法吗?

【问题讨论】:

  • 使用x.iat[0] 获取第一个值。 first 做了一件非常不同的事情。

标签: python pandas group-by


【解决方案1】:

尝试使用x.iloc[0] 作为第一个值,使用x.iloc[-1] 作为最后一个值:

df = df.groupby('id').agg(lambda x : x.count() if x.name in ['var1','var2'] else x.iloc[0])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    相关资源
    最近更新 更多