Python 在Pandas中使用fillna()和lambda函数替换NaN值
我试图在Pandas中编写fillna或lambda函数,检查“user_score”列是否为NaN,如果是,则使用另一个数据帧中的列数据。我尝试了两种选择:Python 在Pandas中使用fillna()和lambda函数替换NaN值,python,pandas,Python,Pandas,我试图在Pandas中编写fillna或lambda函数,检查“user_score”列是否为NaN,如果是,则使用另一个数据帧中的列数据。我尝试了两种选择: games_data['user_score'].fillna( genre_score[games_data['genre']]['user_score'] if np.isnan(games_data['user_score']) else games_data['user_score'], inpla
games_data['user_score'].fillna(
genre_score[games_data['genre']]['user_score']
if np.isnan(games_data['user_score'])
else games_data['user_score'],
inplace = True
)
# but here is 'ValueError: The truth value of a Series is ambiguous'
及
我的数据帧:
游戏数据
体裁评分
我很高兴能得到任何帮助 使用:
您还可以直接与用户按类型映射进行评分:
用户评分按游戏类型=游戏数据。游戏类型。地图类型。用户评分
games_data.user_score=games_data.user_score.fillnauser_score_by_流派
顺便说一句,如果games_data.user_分数永远不会偏离流派_分数值,您可以跳过填充,直接分配给games_data.user_分数:
games_data.user_score=games_data.genre.mapgenre_score.user_score
熊猫的内置功能也很有效,更简洁:
df1.user_score.wheredf1.user_score.isna,df2.user_score,inplace=True我找到了解决方案的一部分 我使用series.map:
user_score_by_genre = games_data['genre'].map(genre_score['user_score'])
然后我用@MayankPorwal回答:
games_data['user_score'] = np.where(games_data['user_score'].isna(), user_score_by_genre, games_data['user_score'])
我不确定这是否是最好的方法,但它对我有效。@MaxB答案对你有用吗?谢谢,但这并不是我所需要的。df1和df2它们有不同的大小,因此我必须为df1中的每个NaN值从df2中按键选择一个特定值,如我的示例df2[df1['genre']['user_score']中所示。像结果它可以是类似于df1['user\u score']=np的东西。其中df1['user\u score']。isna,df2[df1['genre']['user\u score'],df1['user\u score'],谢谢你的回答,但这并不是我需要的。请在Mayank Porwal的回答中查看我的评论刚刚做了,你可以查看问题。我也得到一个解决方案,将张贴它soon@MaxB看起来你已经有了一个有效的解决方案,但仅供参考,我添加了另一个选项,直接使用fillnauser_score_by_流派。嗯,它更漂亮:谢谢你,我认为这不是一个好主意,因为我用每种游戏类型的平均分数和游戏类型的分数来填补游戏数据的空白。这种方法会模糊数据。
user_score_by_genre = games_data['genre'].map(genre_score['user_score'])
games_data['user_score'] = np.where(games_data['user_score'].isna(), user_score_by_genre, games_data['user_score'])