【问题标题】:Search for strings from df2.col2 as substrings in df1.col1 and replace them with strings from df2.col1搜索 df2.col2 中的字符串作为 df1.col1 中的子字符串,并将其替换为 df2.col1 中的字符串
【发布时间】:2019-11-07 19:33:06
【问题描述】:

还没能得到想要的结果:

我有一个数据框:

df1 = pd.DataFrame({"Address":['1024 FRANCIS CIRC', '2077 JOHNSON CLF', '1099 S ARLINGTON RDGE ROAD']})

我有第二个数据框:

df2 = pd.DataFrame({"Address_Type":['CIRCLE','CIRCLE','CLIFF','RIDGE','RIDGE'],
"Abbreviation":['CIR','CIRC','CLF','RDG','RDGE']})

我想在 df1.Address 中搜索 df2.Abbreviation 中的字符串,如果找到,将其更改为 df2.Address_Type 中的相应字符串。

我想看到的结果是:

df1 = pd.DataFrame("Address":['1024 FRANCIS CIRCLE', '2077 JOHNSON CLIFF', '1099 S ARLINGTON RIDGE ROAD']})

一直在尝试使用函数调用的 lambda 函数和 lambda 函数,但没有雪茄。

【问题讨论】:

    标签: python-3.x str-replace


    【解决方案1】:

    试试这个:

    for i in range(len(df1['Address'])):
    
        str_item = df1['Address'].iloc[i].split( )
    
        for j in range(len(str_item)):
    
            index_row = df2.loc[df2['Abbreviation'] == '{}'.format(str_item[j])].index.values.astype(int)
    
        if index_row > 0:
    
            str_item[j] = df2['Address_Type'].iloc[index_row].values[0]
    
        str_new = ' '.join(str_item)
    
       df1['Address'].iloc[i] = str_new
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-08
      • 1970-01-01
      相关资源
      最近更新 更多