【问题标题】:I want to use fillna Mean to fill the missing value. I want to do that according to product Id我想使用 fillna 均值来填充缺失值。我想根据产品 ID 来做
【发布时间】:2020-02-22 23:24:57
【问题描述】:
product_ID Prodcut_Price   Product_monthly_sale
   1           24                2000.00
   1           Nan               2500.00    
   1           26                Nan
   1           28                2700.00
   2           25                2400.00
   2           Nan               Nan
   2           27                2600.00 

我想根据product_id填写product_price列和product_sale列的nan值

【问题讨论】:

  • 提供您预期的输出。还要说明你尝试了什么
  • 也许你可以先做 df.groupby('product_id').mean() 并将其临时存储。然后遍历dataframe,遇到Nan时,从临时dataframe中获取值。
  • 我希望 NAN 值是使用 Fillna(median or mean) 替换但基于 product_id
  • 到底是什么问题?你有没有尝试过,做过任何研究? Stack Overflow 不是免费的代码编写服务。 请参阅:tourHow to Askhelp centermeta.stackoverflow.com/questions/261592/…
  • 另外,这怎么不是你之前的问题的重复:stackoverflow.com/questions/60302731/… 你为什么不编辑那个问题呢?

标签: python pandas


【解决方案1】:

创建数据

df = pd.DataFrame({'product_ID':[1,1,3,3,3], 
                   'Prodcut_Price':[1,np.nan,5,np.nan, 9],
                   'Product_monthly_sale':[1,np.nan,5,np.nan, 5]})
df

结果:

    product_ID  Prodcut_Price   Product_monthly_sale
0   1           1.0             1.0
1   1           NaN             NaN
2   3           5.0             5.0
3   3           NaN             NaN
4   3           9.0             5.0

用分组方式填充 nan

df = df[['product_ID']].join(df.groupby("product_ID")
        .transform(lambda x: x.fillna(x.mean())))
df

结果:

    product_ID  Prodcut_Price   Product_monthly_sale
0   1           1.0             1.0
1   1           1.0             1.0
2   3           5.0             5.0
3   3           7.0             5.0
4   3           9.0             5.0

【讨论】:

  • 我想为形状的数据集(300000,600)这样做。无法手动完成。
  • 您可以为此使用 for 循环。查看编辑后的答案
  • 你能解释一下它基本上在做什么吗?
  • @JonathandeMelker - 我认为代码的瓶颈是调用 lambda 函数。
  • @JonathandeMelker - 请不要将我的答案添加到您的解决方案中。
【解决方案2】:

为了提高性能,请避免使用 lambda 函数,而是使用 GroupBy.transform 作为每个组的平均值,使用 DataFrame.fillna

df = df.fillna(df.groupby("product_ID").transform('mean'))
print (df)
   product_ID  Prodcut_Price  Product_monthly_sale
0           1           24.0                2000.0
1           1           26.0                2500.0
2           1           26.0                2400.0
3           1           28.0                2700.0
4           2           25.0                2400.0
5           2           26.0                2500.0
6           2           27.0                2600.0

【讨论】:

  • 我已经使用了这段代码,执行代码需要时间,但它什么也没做
猜你喜欢
  • 1970-01-01
  • 2019-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 1970-01-01
相关资源
最近更新 更多