【问题标题】:Pandas transform: creating two columns with function熊猫变换:用函数创建两列
【发布时间】:2019-07-30 03:54:57
【问题描述】:

我有一个数据框 df

df:

GROUP VALUE
 1     5
 2     2
 1     10
 2     20
 1     7

还有一个函数

import numpy as np
from scipy import stats

def z_score(x):
   z = np.abs(stats.zscore(x))
   c = np.where(x > 5, 1, 0)
   return z,c

我正在尝试借助函数输出和 pandas 转换方法在数据框中创建两列

df['zscore'], df['label'] = a.groupby(['GROUP'])['VALUE'].transform(z_score)

但是运行上面的sn-p后出现如下错误

ValueError: Length of passed values is 2, index implies 3

如何做到这一点?

【问题讨论】:

    标签: python pandas transform apply pandas-groupby


    【解决方案1】:

    你可以在函数中返回DataFrame

    def z_score(x):
       z = np.abs(stats.zscore(x))
       c = np.where(x > 5, 1, 0)
       return pd.DataFrame({'zscore':z,'label':c}, index=x.index)
    
    df[['zscore','label']] = df.groupby(['GROUP'])['VALUE'].apply(z_score)
    print (df)
       GROUP  VALUE    zscore  label
    0      1      5  1.135550      0
    1      2      2  1.000000      0
    2      1     10  1.297771      1
    3      2     20  1.000000      1
    4      1      7  0.162221      1
    

    但为了获得更好的性能,可以更改groupby 的代码,仅用于scorelabel 列数之后的groupby

    def z_score(x):
       z = np.abs(stats.zscore(x))
       return z
    
    df['zscore'] = df.groupby('GROUP')['VALUE'].transform(z_score)
    #lambda function alternative
    #df['zscore'] = df.groupby('GROUP')['VALUE'].transform(lambda x: np.abs(stats.zscore(x)))
    df['label'] = np.where(df['VALUE'] > 5, 1, 0)
    print (df)
       GROUP  VALUE    zscore  label
    0      1      5  1.135550      0
    1      2      2  1.000000      0
    2      1     10  1.297771      1
    3      2     20  1.000000      1
    4      1      7  0.162221      1
    

    【讨论】:

    • @jezrael,有时很难将 groupby 和 transform 之后的操作可视化
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    相关资源
    最近更新 更多