python - How does pandas replace NaN values with mean value using groupby
问题描述
I tried using this to replace the NaN values in the column feature count ( its an integer that ranges from 1 to 10 ) using groupby ( client_id or client _ name ) , however the NaN values do not seem to go.
df['feature_count'].isnull().sum()
The output is :
2254
Now I use:
df['feature_count'].fillna(df.groupby('client_name')['feature_count'].mean(), inplace=True)
But the output remains the same :
df['feature_count'].isnull().sum()
2254
Any other way to replace the NaN values by the means of other non NaN values of the column grouped by their IDs?
解决方案
df.groupby('client_name')['feature_count'].mean()
返回一个系列。
但是您不希望将 null 值替换为 series。相反,您想用从系列映射的平均值替换空值。
因此,您可以使用以下内容:
s = df.groupby('client_name')['feature_count'].mean()
df['feature_count'].fillna(df['client_name'].map(s), inplace=True)
更 Pandorable 将是利用pd.DataFrame.transform
,它为您处理映射部分:
s = df.groupby('client_name')['feature_count'].transform('mean')
df['feature_count'].fillna(s, inplace=True)
推荐阅读
- data-structures - 如何组合数据点的两个属性(每个属性具有相反的影响)以过滤出最佳数据点?
- python - 合并和覆盖两个 DataFrame 中的公共列
- amazon-web-services - 执行 aws-lambda 时出现参数列表太长错误
- c++ - C++:变量“DiscreteGBM::S0”未初始化。始终初始化成员变量(type.6)
- mysql - 从另一表的列中减去一列的总和
- android - 使用 POST 从 API 获取 JSON 对象
- c - 反向词,指针方法
- google-cloud-firestore - 我应该将 QR 码存储为“文本”还是“图像”?
- python - 列出在字典列表中具有字符串日期的日期类型的键 python
- javascript - 为什么引导面板切换在 reactjs 构建版本中不起作用?