如何使用Python在数据框中查找字符串匹配

时间:2019-05-13 15:21:54

标签: python regex pandas sqlite

我正在尝试在文本字符串和数据框的两列(“ tickers”和/或“ company”)之间找到紧密匹配的内容。

这是数据框的示例:

cik     | tickers | company                      |
--------------------------------------------------
1090872 | A       |   Agilent Technologies Inc   |
--------------------------------------------------
4281    | AA      |   Alcoa Inc                  |
--------------------------------------------------
6201    | AAL     |   American Airlines Group Inc|
--------------------------------------------------
8177    | AAME    |   Atlantic American Corp     |
--------------------------------------------------
706688  | AAN     |   Aarons Inc                 |
--------------------------------------------------
320193  | AAPL    |   Apple Inc                  |
--------------------------------------------------

这是某些文本的外观:

text = 'consectetur elementum Apple Inc Agilent Inc. Aenean porttitor porta magna AA American Airlines AAMC Aarons Inc AAPL e plumbs ernum. AA'

我想在此文本中找到所有接近的匹配项,并使输出类似:

The following companies were found in 'text':
- AAPL: Apple Inc
- A: Agilent Technologies Inc
- AA: American Airlines Group Inc
- AAN: Aarons Inc

这是我到目前为止的代码,但是它不完整,我认识到它需要一种不同的方法:

import pandas as pd
import re

data = {'cik': ['1090872', '4281', '6201', '8177', '706688', '320193'], 'ticker': ['A', 'AA', 'AAL', 'AAME', 'AAN', 'AAPL'], 'company': ['Agilent Technologies Inc', 'Alcoa Inc', 'American Airlines Group Inc', 'Atlantic American Corp', 'Aarons Inc', 'Apple Inc']}
df = pd.DataFrame(data, columns=['cik', 'ticker', 'company'])

text = 'consectetur elementum Apple Inc Agilent Inc. Aenean porttitor porta magna AA American Airlines AAMC Aarons Inc AAPL e plumbs ernum. AA'

ticker = df['ticker']
regex = re.compile(r"\b(?:" + "|".join(map(re.escape, ticker)) + r")\b")

matches = re.findall(regex, text)
for match in matches:
    print(match)

1 个答案:

答案 0 :(得分:0)

这就是我要解决的方法。首先根据您的代码进行设置

import pandas as pd
import numpy as np
data = [['1090872', 'A', 'Agilent Technologies Inc'], ['4281', 'AA', 'Alcoa Inc'],
       ['6201', 'AAL', 'American Airlines Group Inc'], ['8177', 'AAME', 'Atlantic American Corp'],
       ['706688', 'AAN', 'Aarons Inc'], ['320193', 'AAPL', 'Apple Inc']]
df = pd.DataFrame(data, columns=['cik', 'tickers', 'company'])
text = "consectetur elementum Apple Inc Agilent Inc. Aenean porttitor porta magna AA American \
Airlines AAMC Aarons Inc AAPL e plumbs ernum. AA"
df['text'] = text
df['found'] = None

company_values = df['company'].values
for val in company_values:
    row = df.loc[df['company'] == val]
    if row['text'].str.contains(val).any():
        df.loc[df['company'] == val, 'found'] = 'Yes'
# filter the results        
df.loc[df['found'] == 'Yes']

我认为使文本成为数据框的一部分,然后搜索实际找到的公司,然后将其记录在df['found']列中,然后可以对其进行过滤以查找公司列表。在这里,我假设数据框仅包含带有其代码的唯一公司名称。