猿问

从另一个数据帧替换数据帧中的值

所以我正在使用带有两个数据框的数据集。数据帧如下所示:


df1:


Item_ID  Item_Name

0        A

1        B

2        C

df2:


Item_slot_1   Item_slot_2  Item_Slot_3

2             2            1

1             2            0

0             1            1

df2 中的值表示来自 df1 的 Item_ID。如何将 df2 中的值从 item_id 替换为实际项目名称,以便 df2 看起来像:


Item_slot_1   Item_slot_2  Item_Slot_3

C             C            B

B             C            A

A             B            B

现实中的数据集要大得多,而且有更多的 id 和名称,而不仅仅是 a、b 和 c


翻过高山走不出你
浏览 125回答 2
2回答

白板的微信

通过创建字典zip并将其传递给applymap, or replaceor applywith map:s = dict(zip(df1['Item_ID'], df1['Item_Name']))#if value not exist in df1['Item_ID'] get None in df2df2 = df2.applymap(s.get)或者:#if value not exist in df1['Item_ID'] get original value in df2df2 = df2.replace(s)或者:#if value not exist in df1['Item_ID'] get NaN in df2df2 = df2.apply(lambda x: x.map(s))print (df2)  Item_slot_1 Item_slot_2 Item_Slot_30           C           C           B1           B           C           A2           A           B           B编辑:您可以按名称为进程指定列:cols = ['Item_slot_1','Item_slot_2','Item_Slot_3']df2[cols] = df2[cols].applymap(s.get)df2[cols] = df2[cols].replace(s)df2[cols] = df2[cols].apply(lambda x: x.map(s))
随时随地看视频慕课网APP

相关分类

Python
我要回答