我想在列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
我在做什么错了?
答案 0 :(得分:0)
我使用matplotlib
只是为了更好地显示结果...您可以使用isnull()
/ 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")