微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有条件的NaN填充不会改变色谱柱或全部变为无

如何解决有条件的NaN填充不会改变色谱柱或全部变为无

我有一个带有Critic_score列的df,该列具有NaN值。我正在尝试用同一平台的评论评分的平均值代替它们。这个问题已经在堆栈溢出中被问过几次了,我使用了4条没有给我期望输出的建议。请告诉我如何解决此问题。

这是df的子集:

x[['Platform','Critic_score']].head()

Platform    Critic_score
0   wii 76.0
1   nes NaN
2   wii 82.0
3   wii 80.0
4   gb  NaN

有关原始df的更多信息:

x.head().to_dict('list')
{'Name': ['wii sports','super mario bros.','mario kart wii','wii sports resort','pokemon red/pokemon blue'],'Platform': ['wii','nes','wii','gb'],'Year_of_Release': [2006.0,1985.0,2008.0,2009.0,1996.0],'Genre': ['sports','platform','racing','sports','role-playing'],'NA_sales': [41.36,29.08,15.68,15.61,11.27],'EU_sales': [28.96,3.58,12.76,10.93,8.89],'JP_sales': [3.77,6.81,3.79,3.28,10.22],'Other_sales': [8.45,0.77,3.29,2.95,1.0],'Critic_score': [76.0,nan,82.0,80.0,nan],'User_score': ['8','8.3','8','rating': ['E','E',nan]}

这些是我尝试过的语句及其输出

1。

x['Critic_score'] = x['Critic_score'].fillna(x.groupby('Platform')['Critic_score'].transform('mean'),inplace = True)

0    None
1    None
2    None
3    None
4    None
Name: Critic_score,dtype: object
x.loc[x.Critic_score.isnull(),'Critic_score'] = x.groupby('Platform').Critic_score.transform('mean')
#no change in column
0    76.0
1     NaN
2    82.0
3    80.0
4     NaN
x['Critic_score'] = x.groupby('Platform')['Critic_score']\
    .transform(lambda y: y.fillna(y.mean()))
#no change in column
0    76.0
1     NaN
2    82.0
3    80.0
4     NaN
Name: Critic_score,dtype: float64
x['Critic_score']=x.groupby('Platform')['Critic_score'].apply(lambda y:y.fillna(y.mean()))
​
x['Critic_score'].head()
​

Out[73]:
0    76.0
1     NaN
2    82.0
3    80.0
4     NaN
Name: Critic_score,dtype: float64

解决方法

x.update(
    x.groupby('Platform').Critic_Score.transform('mean'),overwrite=False)
  • 首先,创建一个新的df,该行具有相同的行数,但每行的平台平均值。

  • 然后用它来更新原始文件

请记住,您的样本只有nes的一行,gb的另一行的得分均为nan,因此没有什么可求平均值的

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。