python - 如何使用 Pandas 将字符串与数据框中的字符串进行比较?

标签 python pandas

假设我有一个字符串存储在 text 中。我想将此字符串与存储在数据框中的字符串列表进行比较,并检查 text 是否包含汽车、飞机等词。对于找到的每个关键字,我想添加 1 个属于相关主题。

| topic      | keywords                                  |
|------------|-------------------------------------------|
| Vehicles   | [car, plane, motorcycle, bus]             |
| Electronic | [television, radio, computer, smartphone] |
| Fruits     | [apple, orange, grape]                    |

我写了下面的代码,但我不是很喜欢。而且它没有按预期工作。

def foo(text, df_lex):

    keyword = []
    score = []
    for lex_list in df_lex['keyword']:
        print(lex_list)
        val = 0
        for lex in lex_list:

            if lex in text:
                val =+ 1
        keyword.append(key)
        score.append(val)
    score_list = pd.DataFrame({
    'keyword':keyword,
    'score':score
    })

有没有办法有效地做到这一点?我不喜欢在我的程序中有太多循环,因为它们看起来效率不高。如果需要,我会详细说明。谢谢。

编辑:例如我的文字是这样的。我让它变得简单,以便于理解。

我今天骑着摩托车去陈列室买了一辆汽车。不幸的是,当我查看我的智能手机时,我收到了一条回家的消息。

所以,我的预期输出应该是这样的。

| topic      | score |
|------------|-------|
| Vehicles   | 2     |
| Electronic | 1     |
| Fruits     | 0     |

EDIT2:在@jezrael 的帮助下,我终于找到了自己的解决方案。

df['keywords'] = df['keywords'].str.strip('[]').str.split(', ')

text = 'I went to the showroom riding a motorcycle to buy a car today. Unluckily, when I checked my smartphone, I got a message to go home.'

score_list = []
for lex in df['keywords']:
    val = 0
    for w in lex:
        if w in text:
            val +=1
    score_list.append(val)
df['score'] = score_list
print(df)

它打印的正是我需要的。

最佳答案

这里有两种仅使用 vanilla python 的替代方法。 首先是感兴趣的数据。

kwcsv = """topic, keywords
Vehicles, car, plane, motorcycle, bus
Electronic, television, radio, computer, smartphone
Fruits, apple, orange, grape
"""

test = 'I went to the showroom riding a motorcycle to buy a car today. Unluckily, when I checked my smartphone, I got a message to go home.'
testr = test
from io import StringIO

StringIO只是用来做可运行的例子,它象征着读一个文件。 然后构造一个kwords字典用于计数。

import csv

kwords = dict()
#with open('your_file.csv') as mcsv:
mcsv = StringIO(kwcsv)
reader = csv.reader(mcsv, skipinitialspace=True)
next(reader, None) # skip header
for row in reader:
    kwords[row[0]] = tuple(row[1:])

现在我们有了要在字典中计数的内容。第一种选择是在文本字符串中进行计数。

for r in list('.,'): # remove chars that removes counts
    testr = testr.replace(r, '')

result = {k: sum((testr.count(w) for w in v)) for k, v in kwords.items()}

或使用正则表达式拆分字符串和计数器的另一个版本。

import re
from collections import Counter

words = re.findall(r'\w+', StringIO(test).read().lower())
count = Counter(words)

result2 = {k: sum((count[w] for w in v)) for k, v in kwords.items()}

并不是说这些中的任何一个都更好,只是仅使用 vanilla python 的替代方案。我个人会使用 re/Counter 版本。

关于python - 如何使用 Pandas 将字符串与数据框中的字符串进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54614109/

相关文章:

python - 如何使用一个事件的返回值(str)作为时间python sdk中第二个事件的输入?

python - 使用numpy为特定值的像素制作掩码数组

python - 作为数据库的 Pandas HDF5

python - 我不能按每一列对 DataFrame 进行分组

python - 按多列groupby进行值计数

python - browser = webdriver.Chrome() 不起作用

python - 永远保持文件打开的风险

python - 如何在 plotly 中添加条形图上方的百分比差异

python - 同月累计

python - 如何推断 pandas 数据框中的类型