当列的值是在 str 切片的特定位置相同的 str 时合并 dfs

Merging dfs when values of columns are str that are identical at specific locations of the str's slice

假设我有两个 dfs 如下:

data1= {'Column': ['01A01', '03C12', '04F23']}
df1=pd.DataFrame(data1)

data2 = {'Plate': ['1A1', '3D14', '1B6']}
df2=pd.DataFrame(data2)

我想从 df1 中找到值 (str),它们的第二个和第三个字母与 df2 的第一个和第二个字母匹配。当它们匹配时,从每个 df 中提取整行并合并它们。 因此,在此示例中,“01A01”和“1A1”应该匹配。

我的方法是这样的:

def letter_matcher(df1, df2, left_key=str, right_key=str): 

    full_list1 = []  
    full_list2 = []
    
    for value1 in df1[left_key]:
        list1 = [value1[1], value1[2]]
        full_list1.append(list1)
        df1['new1'] = full_list2
   
    for value2 in df2[right_key]:
        list2 = [value2[0], value2[1]]
        full_list2.append(list2)
        df2['new2'] = full_list2
        
    df_new = df1.merge(df2, left_on=new1, right_on=new2 , how='inner')
  
    if df_new:
            
            print(df_new.head())
    else:
            print('No result')

感谢您帮助修改代码。

在数据帧之间创建一个公共 key 以识别行并合并它们:

>>> pd.merge(df1.assign(key=df1['Column'].str[1:3]),
             df2.assign(key=df2['Plate'].str[0:2]),
             how='left').drop(columns='key')

  Column Plate
0  01A01   1A1
1  03C12   NaN
2  04F23   NaN

参考merge的文档调整参数how。这里我选择 left 来保留来自 df1 的行。

更新

I need to match several inconsistent letters: df1--> str[1:3] and str [9:], df2--> str[0:2] and str[6:7] , or even a longer str, how the script will look like?

使用apply代替str[]

pd.merge(df1, df2,
         left_on=df1['Column'].apply(lambda x: ''.join([x[1:3], x[9:]])),
         right_on=df2['Plate'].apply(lambda x: ''.join([x[0:2], x[6:7]])))

只需合并切片字符串即可。

下面的代码

df1.merge(df2, how='left', left_on=df1['Column'].str[1:3], right_on=df2['Plate'].str[0:2])