python - 用列中的平均值输入 NaN 并找到缺失值的百分比
问题描述
我想估算该列所有缺失值的平均值Product_Base_Margin
,然后打印每列中缺失值的百分比。
我当前的代码:
import numpy as np
import pandas as pd
df = pd.read_csv('https://query.data.world/s/Hfu_PsEuD1Z_yJHmGaxWTxvkz7W_b0')
df = df[~np.isnan(df['Product_Base_Margin'])]
print(round(100*(df.isnull().sum()/len(df.index)), 2))
预期输出:
Ord_id 0.00
Prod_id 0.00
Ship_id 0.00
Cust_id 0.00
Sales 0.24
Discount 0.65
Order_Quantity 0.65
Profit 0.65
Shipping_Cost 0.65
Product_Base_Margin 0.00
dtype: float64
我究竟做错了什么?
解决方案
我曾经matplotlib
只是为了更好地显示结果...您可以使用isnull()
/找到 NaN 的数量isna()
插入意味着它是 NaN 的位置。 fillna()
import numpy as np
import pandas as pd
df = pd.read_csv('https://query.data.world/s/Hfu_PsEuD1Z_yJHmGaxWTxvkz7W_b0')
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1,2, figsize=[10,5],
sharey=True, sharex=False)
df.loc[:,"Product_Base_Margin"].isnull().to_frame().value_counts().plot(ax=ax[0], kind="bar")
df.loc[:,"Product_Base_Margin"].fillna(df.loc[:,"Product_Base_Margin"].mean(), inplace=True)
df.loc[:,"Product_Base_Margin"].isnull().to_frame().value_counts().plot(ax=ax[1], kind="bar")
推荐阅读
- xsd - Java XSD - 使用自定义集合类型
- c++ - 尝试使用 libcurl 设置 IBM Watson 的 TTS 服务时出现问题
- php - Livewire 提交表单在数据库中创建重复记录
- html - 如何用svg背景做磨砂玻璃效果?
- sorting - Ansible如何按元素子字符串的降序对数组进行排序
- python - 如何在 discord.py bot 中实现 sql 数据库
- google-chrome - 我们可以自定义实时网站颜色并将更改保存到本地浏览器吗?
- python - 针对“输入包含 NaN、无穷大或对于 dtype('float64') 而言太大的值”采取适当措施。错误
- ubuntu - 在“start-dfs.sh”之后出现错误“权限被拒绝(公钥,密码)”
- c++ - 不完全理解顶点属性的概念