【发布时间】:2020-01-01 18:13:56
【问题描述】:
我将单词袋作为列表格式的元素。我正在尝试搜索这些单词中的每一个是否仅在它“开始于”列表中的元素时才出现在熊猫数据框中。我试过用“startswith”和“contains”来比较。
代码:
import pandas as pd
# list of words to search for
searchwords = ['harry','harry potter','secret garden']
# Data
l1 = [1, 2, 3,4,5]
l2 = ['Harry Potter is a great book',
'Harry Potter is very famous',
'I enjoyed reading Harry Potter series',
'LOTR is also a great book along',
'Have you read Secret Garden as well?'
]
df = pd.DataFrame({'id':l1,'text':l2})
df['text'] = df['text'].str.lower()
# Preview df:
id text
0 1 harry potter is a great book
1 2 harry potter is very famous
2 3 i enjoyed reading harry potter series
3 4 lotr is also a great book along
4 5 have you read secret garden as well?
尝试#1:
When I run this command it picks it up and gives me the results through out the text column. Not what I am looking for. I just used to check if I am doing things right for an example reasons for my understanding.
df[df['text'].str.contains('|'.join(searchwords))]
尝试 #2: 当我运行此命令时,它什么也不返回。这是为什么?我做错了什么?当我将 'harry' 搜索为单个时,它可以工作,但当我传入元素列表时却不行。
df[df['text'].str.startswith('harry')] # works with single string.
df[df['text'].str.startswith('|'.join(searchwords))] # returns nothing!
【问题讨论】:
标签: python python-3.x pandas