首页 > 解决方案 > 如何使用 Python 在数据框中查找字符串匹配项

问题描述

我试图在一个文本字符串和我的数据框的两列之间找到紧密匹配——“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)

标签: pythonregexpandassqlite

解决方案


以下是我将如何解决这个问题。首先根据您的代码进行设置

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']列中,然后您可以对其进行过滤以查找公司列表。在这里,我假设数据框仅包含唯一的公司名称及其代码。


推荐阅读