我正在研究来自 Kaggle 的 titanic 数据集,并尝试根据来自其他列的信息替换一列中的 NaN 值。
在我的具体示例中,我试图用男性一等舱乘客的平均年龄替换一等舱男性乘客的未知年龄。
我该怎么做?
我已经能够对数据进行分段并替换该新数据帧的空值,但它不会延续到原始数据帧,我不太清楚如何做到这一点。
这是我的代码:
missingage_1stclass_male = pd.DataFrame(
titanic[
(titanic['Age'].isnull()) &
(titanic['Pclass'] == 1) &
(titanic['Sex'] == 'male')
]
)
missingage_1stclass_male.Age.fillna(40.5, inplace=True)
我包含所有值的原始数据框名为 titanic。
最佳答案
I am trying to replace the unknown age of male, 1st class passengers with the average age of male, 1st class passengers.
您可以将问题分为两步。首先计算男性一等舱乘客的平均年龄:
mask = (df['Pclass'] == 1) & (df['Sex'] == 'male')
avg_filler = df.loc[mask, 'Age'].mean()
然后更新满足您标准的值:
df.loc[df['Age'].isnull() & mask, 'Age'] = avg_filler
关于python - 如何在其他列满足特定条件的情况下替换 NaN 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52121785/