【发布时间】:2020-01-02 09:25:08
【问题描述】:
我想在groupby('score') 之后添加特定列patient 的第25 个百分位信息,但出现如下所示的错误。
import pandas as pd
raw_data = {'patient': [242, 151, 111,122, 342],
'obs': [1, 2, 3, 1, 2],
'treatment': [0, 1, 0, 1, 0],
'score': ['strong', 'weak', 'weak', 'weak', 'strong']}
df = pd.DataFrame(raw_data, columns = ['patient', 'obs', 'treatment', 'score'])
df
patient obs treatment score
0 242 1 0 strong
1 151 2 1 weak
2 111 3 0 weak
3 122 1 1 weak
4 342 2 0 strong
quantile_25 = []
df_g=df.groupby("score")
for col in df.keys():
if col=='patient':
Q1 = df_g.apply(lambda _df: _df.np.percentile(_df[feature], q = 25))
quantile_25.append(Q1)
else:
pass
df['std_dev_patient'] = df.score.map(quantile_25[0])
AttributeError: 无法访问 >'DataFrameGroupBy' 对象的可调用属性 'groupby',请尝试使用 'apply' 方法
我想保留相同的for loop,因为我想将其他统计信息添加为新列。
谢谢
预期输出
patient obs treatment score quantile_25
0 242 1 0 strong ..
1 151 2 1 weak ..
2 111 3 0 weak ..
3 122 1 1 weak ..
4 342 2 0 strong ..
【问题讨论】:
-
这一行
_df.np.percentile(_df[feature], q = 25)对我来说是不编译,说DataFrame没有np属性,是不是np.percentile(_df[feature], q = 25)?还有feature是什么? -
try: df['new_col']=df.groupby('score')['patient'].transform(lambda x: np.percentile(x,25)) except KeyError: pass