代码之家  ›  专栏  ›  技术社区  ›  daiyue

pandas ValueError:转换无法生成聚合结果

  •  2
  • daiyue  · 技术社区  · 6 年前

    我有以下的 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
    

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

    2 回复  |  直到 6 年前
        1
  •  2
  •   jezrael    6 年前

    问题是 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
    

    因此,使用按组排序值的解决方案 DataFrame.sort_values 前2列 groupby('id') :

    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]
    
        2
  •  3
  •   rafaelc    6 年前

    IIUC,你必须在GROPBY对象中使用变换,所以只需用现有的任意索引重新组合即可。

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