lambda函数引用未在函数中指定的列值

时间:2019-09-13 00:34:29

标签: python pandas pandas-groupby

我遇到一种情况,我想在训练集中使用groupby的结果来填充测试集的结果。

我认为在熊猫中没有直接的方法可以做到这一点,因此我尝试在测试集中的列上使用apply方法。

我的情况:

我想使用MSZoning列中的平均值来推断LotFrontage列中的缺失值。

如果我在训练集上使用groupby方法,我会得到:

train.groupby('MSZoning')['LotFrontage'].agg(['mean', 'count'])

给予.....

enter image description here

现在,我想使用这些值在我的 test 集合上估算缺少的值,所以我不能只使用transform方法。

相反,我创建了一个想要传递给apply方法的函数,可以在此处看到它:

def fill_MSZoning(row):
    if row['MSZoning'] == 'C':
        return 69.7
    elif row['MSZoning'] == 'FV':
        return 59.49
    elif row['MSZoning'] == 'RH':
        return 58.92
    elif row['MSZoning'] == 'RL':
        return 74.68
    else:
        return 52.4

我这样调用函数:

test['LotFrontage'] = test.apply(lambda x: x.fillna(fill_MSZoning), axis=1)

现在,即使我没有指定,LotFrontage列的结果也与Id列相同。

知道发生了什么吗?

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以这样做

import pandas as pd
import numpy as np

## creating dummy data
np.random.seed(100)

raw = {
    "group": np.random.choice("A B C".split(), 10),
    "value": [np.nan if np.random.rand()>0.8 else np.random.choice(100) for _ in range(10)]
}

df = pd.DataFrame(raw)
display(df)

## calculate mean
means = df.groupby("group").mean()
display(means)

用组均值填充

## fill with mean value
def fill_group_mean(x):
    group_mean = means["value"].loc[x["group"].max()]
    return x["value"].mask(x["value"].isna(), group_mean)


r= df.groupby("group").apply(fill_group_mean)
r.reset_index(level=0)

输出

group   value
0   A   NaN
1   A   24.0
2   A   60.0
3   C   9.0
4   C   2.0
5   A   NaN
6   C   NaN
7   B   83.0
8   C   91.0
9   C   7.0



group   value
0   A   42.00
1   A   24.00
2   A   60.00
5   A   42.00
7   B   83.00
3   C   9.00
4   C   2.00
6   C   27.25
8   C   91.00
9   C   7.00