首页 文章

Pandas New Column基于DataFrame中找到的字符串

提问于
浏览
2

尝试将一个DataFrame中的ID值与另一个DataFrame中的字符串列进行匹配,以创建新的ID字段 .

我有两个数据帧,一个只有一个文本ID列:

DF1

ID
elf
orc
panda

另一个数据帧具有不同的ID但文本列将包含来自第一个DataFrame(DF1)的ID值:

DF2

AltID Text
1     The orc killed the dwarf
2     The elf lives in the woods
3     The panda eats bamboo

这样我就可以在第二个Dataframe(DF2)中创建New ID列,如果找到文本,它将如下所示:

NewID
orc
elf
panda

我应该使用lambda函数还是np.where()?

提前致谢 .

编辑:

如果它需要完全匹配怎么办?例如,我有这一行文字,但不想匹配'orc'

AltID  Text
4      The orchestra played too long

并希望它为NewID输出'None',N / A或那种性质的东西?

2 回答

  • 2

    直截了当使用 str.extract

    df2['New ID'] = df2.Text.str.extract('({})'.format('|'.join(df1.ID)), expand=False)
    
    df2
    
       AltID                        Text New ID
    0      1    The orc killed the dwarf    orc
    1      2  The elf lives in the woods    elf
    2      3       The panda eats bamboo  panda
    
  • 2

    一个小技巧 .

    df2.Text.replace(dict(zip(df1.ID,df1.index)),regex=True).map(df1.ID)
    Out[1004]: 
    0      orc
    1      elf
    2    panda
    Name: Text, dtype: object
    

相关问题