【问题标题】:pandas ValueError: transforms cannot produce aggregated resultspandas ValueError:转换无法产生聚合结果
【发布时间】:2019-01-17 00:12:57
【问题描述】:

我有以下df

type      id      date         code
exact    9720    2017-10-01    515
exact    9720    2017-10-01    515
fuzzy    8242    2017-11-01    122
fuzzy    8242    2017-11-01    122

我在尝试

exact_rows = df['type'] != 'fuzzy'
grouped = df.loc[~exact_rows].groupby('id').apply(
            lambda g: g.sort_values('date', ascending=True))

a = np.where(grouped['code'].transform('nunique') == 1, 20, 0)

但我遇到了一个错误,

ValueError: transforms cannot produce aggregated results

我想知道如何解决这个问题。

【问题讨论】:

    标签: python python-3.x pandas dataframe pandas-groupby


    【解决方案1】:

    IIUC,你必须在 groupby 对象中使用转换,所以只需使用现有的任何索引重新组合

    grouped.groupby(grouped.index)['code'].transform('nunique')
    

    【讨论】:

      【解决方案2】:

      问题是groupby.apply 返回DataFrame,而不是DataFrameGroupBy 对象:

      grouped = df.loc[~exact_rows].groupby('id').apply(
                  lambda g: g.sort_values('date', ascending=True))
      
      print (grouped)
               type    id        date  code
      id                                   
      8242 2  fuzzy  8242  2017-11-01   122
           3  fuzzy  8242  2017-11-01   122
      

      因此,对每组值进行排序的解决方案是在groupby('id') 之前使用DataFrame.sort_values 两列:

      exact_rows = df['type'] != 'fuzzy'
      grouped = df.loc[~exact_rows].sort_values(['id','date'], ascending=True).groupby('id')
      
      a = np.where(grouped['code'].transform('nunique') == 1, 20, 0)
      print (a)
      [20 20]
      

      【讨论】:

        猜你喜欢
        • 2021-08-03
        • 2019-12-10
        • 2016-07-21
        • 1970-01-01
        • 1970-01-01
        • 2015-12-15
        • 2017-04-18
        相关资源
        最近更新 更多