如何使用 pandas map() 函数,而不覆盖不匹配的项目?

Mos*_*she 3 python pandas

在我之前的问题中:如何有效地替换 pandas 中的数据框之间的项目?

我得到了一个可以使用 map() 函数的解决方案,但它会覆盖不匹配的项目。

如果我有 2 df

df = pd.DataFrame({'Ages':[20, 22, 57, 250], 'Label':[1,1,2,7]})
label_df = pd.DataFrame({'Label':[1,2,3], 'Description':['Young','Old','Very Old']})
Run Code Online (Sandbox Code Playgroud)

我想将 df 中的标签值替换为 label_df 中的描述,但如果索引之间不匹配,则保留原始值。

我得到了什么df['Label'] = df['Label'].map(label_df.set_index('Label')['Description'])

{'Ages':[20, 22, 57, 250], 'Label':['Young','Young','Old', nan]}
Run Code Online (Sandbox Code Playgroud)

想要的结果:

{'Ages':[20, 22, 57, 250], 'Label':['Young','Young','Old', 7]}
Run Code Online (Sandbox Code Playgroud)

Sea*_*ean 7

您可以在不匹配的情况.fillna()下进一步使用原始列来.map()恢复原始值,如下所示:

df['Label'] = df['Label'].map(label_df.set_index('Label')['Description']).fillna(df['Label'])
Run Code Online (Sandbox Code Playgroud)

或者,也可以使用.replace()which does not set non-match to NaN(保留不匹配值),如下:

df['Label'] = df['Label'].replace(dict(zip(label_df['Label'], label_df['Description'])))
Run Code Online (Sandbox Code Playgroud)

结果:

print(df)

   Ages  Label
0    20  Young
1    22  Young
2    57    Old
3   250      7
Run Code Online (Sandbox Code Playgroud)