python - 在 Pandas 中使用 fillna() 和 lambda 函数替换 NaN 值

标签 python pandas

我正在尝试在 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

我的数据框:

游戏数据

enter image description here

流派评分

enter image description here

我很乐意提供任何帮助!

最佳答案

您也可以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/

相关文章:

python - 将 matplotlib 颜色图转换为 seaborn 调色板

python - 从 Pandas 中不同数据框中的另一个匹配列更新数据框中的列值

Python Pandas 匹配来自另一个 Dataframe 的最接近索引

python - 如何在 Pandas ,python中加入两个或多个DataFrame

python - Pandas groupby 保持顺序

Python调试: How to step into another python scripts?

python - 在 Python 中,如何防止类定义被多次包含?

python - 当值具有实体时,Selenium WebDriver get_attribute 返回 href 属性的截断值

Python 类派生自 pandas DataFrame,具有 list/DataFrame 属性

python - DataFrame 应用并返回可变多行?