我有一个数据帧 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
我正在尝试借助函数输出和熊猫转换方法在数据框中创建两列
df['zscore'], df['label'] = a.groupby(['GROUP'])['VALUE'].transform(z_score)
但是在运行上述代码片段后收到以下错误
ValueError: Length of passed values is 2, index implies 3
如何实现这一点?
您可以在函数中返回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
但是为了获得更好的性能,可以更改仅用于score
的groupby
代码,并在超出groupby
后label
列计数:
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