[英]Return value in referencing column of dataframe with apply/lambda function
[英]lambda function referencing a column value not specified in function
我遇到一種情況,我想在訓練集中使用groupby
的結果來填寫測試集的結果。
我認為在熊貓中沒有直接的方法可以做到這一點,因此我嘗試在測試集中的列上使用apply
方法。
我的情況:
我想用平均值從我MSZoning
列推斷為我的缺失值LotFrontage
列。
如果我在訓練集上使用groupby
方法, groupby
得到以下信息:
train.groupby('MSZoning')['LotFrontage'].agg(['mean', 'count'])
給.....
現在,我想使用這些值在測試集上插入缺失值,因此我不能只使用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
列相同。
知道發生了什么嗎?
你可以這樣
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.