【问题标题】:Error when adding new column to data frame after grouped data process分组数据处理后向数据框中添加新列时出错
【发布时间】: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

标签: python pandas


【解决方案1】:

这是一个不使用 apply 的解决方案:

df_g=df.groupby("score")
for col in df.columns:
    if col=='patient':
        df['std_dev_patient'] = df_g[col].transform(lambda group: np.percentile(group, q=25))
    else:
        pass

输出:

   patient  obs  treatment   score  std_dev_patient
0      242    1          0  strong            267.0
1      151    2          1    weak            116.5
2      111    3          0    weak            116.5
3      122    1          1    weak            116.5
4      342    2          0  strong            267.0

【讨论】:

    猜你喜欢
    • 2018-03-07
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 2020-11-08
    • 2023-03-14
    • 2020-02-24
    • 2017-09-08
    相关资源
    最近更新 更多