使用 pandas 中 dataframe1 中一列的值查找 dataframe2 中特定列的值

find the value of a specific column in dataframe2 using the value of one column in the dataframe1 in pandas

我在网上搜索了一下。我没有找到我要找的确切案例。 我需要帮助。我有两个数据框,其中一列包含相似的项目。

>>> df1
         ID       Item
0  0667170D      Apple
1  0644304D     Orange
2  0655323D  Pineapple
3  06284A3D     Banana
>>> df2
          ID    Item
0   TY671756  Carrot
1   JG44454D  Banana
2   07753DDD  Orange
3   0628456D   Apple

我有一个 forloop,它将比较两个数据帧之间的 Item 列并获得最匹配的那些。例如:我从 'df2' 中取出苹果并将其与 df1 中的 'Item' 列进行比较。我找到 apple 并将其更新为 df2 中的新列作为匹配项。现在我想在 'df1' 中找到 apple 的 'ID' 也用于匹配的项目,在本例中为 apple。我想将 df1 中 apple 的 'ID' 更新为 df2 中的新列。

我是否也可以在同一个 forloop 中执行此操作?这样我就得到了一个更新的 df2,其中包含在 df1 中找到的匹配项及其 ID 号。

list1 = df2['Item']
list2 = df1['Item']

for i in list1:
   df2['Item'] = [difflib.get_close_matches(i, list2)]

Merge 列上的两个 dfs Item

df3=df1.merge(df2,on="Item")

这将为您提供来自两个数据框的匹配项及其 ID

   ID_x    Item      ID_y
0  0667170D   Apple  0628456D
1  0644304D  Orange  07753DDD
2  06284A3D  Banana  JG44454D

如果您还想保留不匹配的项目:

df1.merge(df2,on="Item",how="outer")

       ID_x       Item      ID_y
0  0667170D      Apple  0628456D
1  0644304D     Orange  07753DDD
2  0655323D  Pineapple       NaN
3  06284A3D     Banana  JG44454D
4       NaN     Carrot  TY671756

如果需要,您可以重命名列。

我认为需要通过字典查找 - 输出是列表,因为匹配了一个或多个值:

list1 = df2['Item']
list2 = df1['Item']

d = df1.set_index('Item')['ID']
df2['new'] = [[d[x] for x in difflib.get_close_matches(i, list2)] for i in list1]
print (df2)
         ID    Item         new
0  TY671756  Carrot          []
1  JG44454D  Banana  [06284A3D]
2  07753DDD  Orange  [0644304D]
3  0628456D   Apple  [0667170D]

编辑:输出两列使用loop解决方案:

list1 = df2['Item']
list2 = df1['Item']
d = df1.set_index('Item')['ID']

id2, item2 = [], []
for i in list1:
     out =  difflib.get_close_matches(i, list2)
     id2.append([d[x] for x in out])
     item2.append(out)

df2['id2new'] = id2    
df2['item2new'] = item2
print (df2)
         ID    Item      id2new  item2new
0  TY671756  Carrot          []        []
1  JG44454D  Banana  [06284A3D]  [Banana]
2  07753DDD  Orange  [0644304D]  [Orange]
3  0628456D   Apple  [0667170D]   [Apple]

如果您想使用 for 循环执行此操作,我认为可以使用下面的代码。否则你可以使用@Sruthi V 的答案。

newColumn = []
for value in df2['Item'].values:
    if (len(df1[df1['Item']==value].values) > 0):
        newColumn.append(df1[df1['Item']==value].iloc[0,0])
    else:
        newColumn.append(np.NaN)

df2['NewColumn'] = newColumn


>>> df2

         ID    Item NewColumn
0  TY671756  Carrot       NaN
1  JG44454D  Banana  06284A3D
2  07753DDD  Orange  0644304D
3  0628456D   Apple  0667170D