資料集包含一個 Pclass 列,其值為 (1, 2, 3) 和 Age。Age 列有一些空值。我想用不同班級的人的中位年齡替換那些空值。一等人的平均年齡是 37 歲,二等人是 29 歲,三等人是 24 歲。
所以這是我想要做的代碼:
def fill_age(x):
if pd.isna(x['Age']) and x['Pclass'] == 1:
return 37
elif pd.isna(x['Age']) and x['Pclass'] == 2:
return 29
elif pd.isna(x['Age']) and x['pclass'] == 3:
return 24
else:
return x['Age']
df['Age'] = df.apply(fill_age)
但這是我得到的錯誤:
KeyError Traceback (most recent call last)
<ipython-input-126-7375a6b3c119> in <module>
----> 1 df['Age'] = df.apply(fill_age)
KeyError: 'Age'
請讓我知道我做錯了什么。先感謝您。
uj5u.com熱心網友回復:
使用DataFrame.apply每個axis=1:
df['Age'] = df.apply(fill_age, axis=1)
對于按字典Series.fillna映射的矢量化(更快)替代使用:Series.map
df['Age'] = df['Age'].fillna(df['Pclass'].map({1:37,2:29,3:24}))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/419174.html
標籤:
