如何在两个数据框之间匹配并提取值?

时间:2020-02-24 20:04:22

标签: python-3.x pandas

我有两个df:

df1:

col1      col2
text        1 

df2:

col1
text 123

我想查看df1.col1中的值是否在df2.col1中,如果是,则存在该值,我想将df2.col1的值拉出到df1中的新列中。

更新的df1:

col1      col2     col_extracted
text        1         text 123

我最能弄清的是进行字符串匹配并返回一个布尔值,如下所示:

df1['col1'].isin(df2['col1'])

但是,由于我正在进行部分字符串匹配,所以我在匹配中得到了FALSE。

1 个答案:

答案 0 :(得分:1)

我询问数据帧的长度是因为搜索/匹配多个字符串模式通常很慢。您的数据非常小,因此不会有问题。这是一个解决方案:

function changeString(currentString, append) {
  try {
    if (typeof append != 'string') {
      throw new Error("Cannot change string!");
    }
    
    console.log(currentString + append);
    
  } catch (er){
    console.error("I'm being logged from inside a catch block because an error was thrown");
    //DO WHATEVER YOU NEED TO FIX THE ERROR AND ALERT THE USER HERE
  }
}

changeString("I wont show up in the console", null)

输出:

pd.concat((df1, 
           df2[df2['col1'].str.contains(df1.col1.iloc[0])]
               .add_suffix('_extracted')
          ), axis=1)
相关问题