简体   繁体   English

将pandas列中的字符串与另一个pandas列中的字符串进行比较

[英]Compare string in a column of pandas with string from another pandas column

I have the following pandas 我有以下熊猫

df:


colA

abc dbe fec
ghi jkl ref
sgsh hjo 


df2:


colB        colC

hjo              12
hhh chk          14
eee abc          17

I want to compare words from the string from each column in df with each word from the strings in colB of df2. 我想比较df中每列的字符串中的单词与df2中colB中字符串中的每个单词。 If match found I want to add corresponding colC to df1. 如果找到匹配,我想将相应的colC添加到df1。 If any word is matched with colB, it should stop and move to the next column. 如果任何单词与colB匹配,它应该停止并移动到下一列。

Result: 结果:

newdf:


colA             colC

abc dbe fec       17
ghi jkl ref       none
sgsh hjo          12

What is the fastest way to do this(huge dataset) 最快的方法是什么(庞大的数据集)

As mentioned in the solution, 如解决方案中所述,

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' 

Use this: 用这个:

Make a dictionary of the reference database: 制作参考数据库的字典:

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

create a pattern: 创建一个模式:

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

Use s.str.extract and s.map() 使用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

EDIT for escape character and space match in each row* (Not sure if best way, but works)* 编辑每行中的转义字符和空格匹配* (不确定是否最佳方式,但有效)*

Considering the df2 is : 考虑到df2是:

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

and df1 being same as your example: 和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

you would notice that columns having spaces are converted to rows having the same values 您会注意到具有空格的列将转换为具有相同值的行

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM