【问题标题】:Compare string in a column of pandas with string from another pandas column将 pandas 列中的字符串与另一个 pandas 列中的字符串进行比较
【发布时间】:2019-06-17 03:01:12
【问题描述】:

我有以下熊猫

df:


colA

abc dbe fec
ghi jkl ref
sgsh hjo 


df2:


colB        colC

hjo              12
hhh chk          14
eee abc          17

我想将 df 中每一列的字符串中的单词与 df2 的 colB 中的字符串中的每个单词进行比较。如果找到匹配项,我想将相应的 colC 添加到 df1。如果任何单词与 colB 匹配,它应该停止并移动到下一列。

结果:

newdf:


colA             colC

abc dbe fec       17
ghi jkl ref       none
sgsh hjo          12

最快的方法是什么(巨大的数据集)

正如解决方案中提到的,

pat:  

 '(Absolute Plumbing|D\xc3\xa9jeuner Eggcetera|Ivy Garcia, LMT|Native Bloom Landscape and Design|Seay\'s|Thulasi Kitchen|Liyuen|Viva Photo Booth|Cleopatra Internet Cafe|R&B\'s Pizza Place|Hilton Toronto/Markham Suites Conference Centre & Spa|Hegel Yoga|Boonda\'s|San Tan Aikido Kokikai|Mega Motors|Blue Sky Nails & Spa|Restaurant Cinq Epices|North East Auto Credit|Blind Tiger|T & S Towing' 

【问题讨论】:

    标签: python database string pandas search


    【解决方案1】:

    使用这个:

    制作参考数据库的字典:

    d = dict(zip(df2.colB,df2.colC))
    #{'hjo': 12, 'hhh chk': 14, 'abc': 17}
    

    创建模式:

    pat = r'({})'.format('|'.join(d.keys()))
    #'(hjo|hhh chk|abc)'
    

    使用s.str.extracts.map()

    df['colC']=df.colA.str.extract(pat, expand=False).dropna().map(d)
    print(df)
    
             colA  colC
    0  abc dbe fec  17.0
    1  ghi jkl ref   NaN
    2     sgsh hjo  12.0
    

    编辑每行中的转义字符和空格匹配*(不确定是否最好,但可行)*

    考虑到df2 是:

         colB  colC
    0      hjo    12
    1  hhh ref    14
    2      abc    17
    

    和 df1 与您的示例相同:

        colA
    0   abc dbe fec
    1   ghi jkl ref
    2   sgsh hjo
    
    import re
    df_split=pd.DataFrame(df2.colB.str.split(' ').tolist(),index=df2.colC).stack().reset_index(0).rename(columns={0:'colB'}).reindex(df2.columns,axis=1)
    print(df_split)
    
      colB  colC
    0  hjo    12
    0  hhh    14
    1  ref    14
    0  abc    17
    

    您会注意到带有空格的列会转换为具有相同值的行

    d = dict(zip(df_split.colB,df_split.colC))
    #{'hjo': 12, 'hhh': 14, 'ref': 14, 'abc': 17}
    keys=[re.sub('[^A-Za-z0-9]+', '', i) for i in d.keys()]
    pat = r'({})'.format('|'.join(keys))
    df['colC']=df.colA.str.extract((pat),expand=False).map(d)
    print(df)
              colA  colC
    0  abc dbe fec    17
    1  ghi jkl ref    14
    2    sgsh hjo     12
    

    【讨论】:

    • @JerryGeorge 尝试 EDIT 下的部分以获取模式。
    • @JerryGeorge 检查 EDIT 下的部分
    猜你喜欢
    • 1970-01-01
    • 2015-04-04
    • 2016-06-25
    • 2020-11-09
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    相关资源
    最近更新 更多