我正在尝试在 Pandas 中编写 fillna() 或 lambda 函数来检查“user_score”列是否为 NaN,如果是,则使用来自另一个 DataFrame 的列数据。我尝试了两种选择:
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.apply(
lambda row:
genre_score[row['genre']]['user_score']
if np.isnan(row['user_score'])
else row['user_score'],
axis=1
)
# but here is 'KeyError' with another column from games_data
我的数据框:
游戏数据
流派评分
我很乐意提供任何帮助!
最佳答案
您也可以fillna()
直接使用 user_score_by_genre
映射:
user_score_by_genre = games_data.genre.map(genre_score.user_score)
games_data.user_score = games_data.user_score.fillna(user_score_by_genre)
顺便说一句,如果 games_data.user_score
永远不会偏离 genre_score
值,您可以跳过 fillna()
并直接分配给 games_data.user_score
:
games_data.user_score = games_data.genre.map(genre_score.user_score)
Pandas 的内置 Series.where
也可以,而且更简洁:
df1.user_score.where(df1.user_score.isna(), df2.user_score, inplace=True)
关于python - 在 Pandas 中使用 fillna() 和 lambda 函数替换 NaN 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66843142/