首页 > 解决方案 > 用列中的平均值输入 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

我究竟做错了什么?

标签: pythonpandasnumpy

解决方案


我曾经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")

在此处输入图像描述


推荐阅读