熊猫用grouby值填充空值

时间:2020-06-24 20:07:10

标签: python pandas

我正在尝试为数据框中的所有数字类型列填充空值。

下面的代码遍历每个数字列,并按分类特征进行分组,并计算目标列的中位数。

然后,我们创建一个新列,该列将复制值(如果存在),但如果为空,则应基于存在n / a的行中的分类值从groupby复制该值。

let provider = new firebase.auth.OAuthProvider('microsoft.com');
provider.setCustomParameters({
  prompt: "consent",
  tenant: "the tenant id provided by outlook",
})

.get_loc之间的功能似乎有问题,这是输出

# fill in numeric nulls with median based on job
for i in dfint:
    print(i)

for i in dfint:
    if i in ["TARGET_BAD_FLAG", "TARGET_LOSS_AMT"]: continue
    print(i)
    group=df.groupby("JOB")[i].median()
    print(group)
    df["IMP_"+i]=df[i].fillna(group[group.index.get_loc(df.loc[df[i].isna(),"JOB"])])
    #the line below works but fills in all nulls with the median for the "Mgr" job category, the code above should find the job category for the null record and pull the groupby value 
    #df["IMP_"+i]=df[i].fillna(group[group.index.get_loc("Mgr")])

有没有办法修改该行以达到预期的效果

2 个答案:

答案 0 :(得分:0)

您这样写:df.loc[df[i].isna(),"JOB"],它将返回给您一个熊猫系列,而不是pandas.Index.get_loc要求的钥匙

答案 1 :(得分:0)

这行吗?

for i in dfint:
    if i in ["TARGET_BAD_FLAG", "TARGET_LOSS_AMT"]: continue
    print(i)
    df[f'IMP_{i}'] = df.groupby('JOB')[i].transform(lambda x: x.fillna(x.median()))