Python:将NULL替换为平均值

问题描述

我是Python的新手,需要您的专家帮助。 我有一个表,其中有多个行用于同一游戏。但是在“评级”列中,此游戏或该游戏的某些单元格为空,有些则不是。 问题:如何用同一游戏的平均评分填充列中的缺失值?

请参见下图的表结构:

enter image description here

提前谢谢!

解决方法

假设您要使用“名称”中组的平均值填充值,则可以组合使用pandas groupbypandas applypandas fillna

>>>df['Rating_score']=df.groupby('Name')['Rating_score'].apply(lambda x:x.fillna(x.mean()))
>>>df
  
    Name     Genere  Rating_score
0  Game1  Adventure          65.0
1  Game1  Adventure          70.0
2  Game1  Adventure          67.5
3  Game2     Racing          59.0
4  Game2     Racing          61.5
5  Game2     Racing          64.0
6  Game3   Shooting          71.0
7  Game3   Shooting          71.0