Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python判断每行是否包含特定的单词_Python - Fatal编程技术网

Python判断每行是否包含特定的单词

Python判断每行是否包含特定的单词,python,Python,我想判断每行是否包含一些特定的单词,如price、key、area等。如果一行包含其中一个单词,则starnum列将为1。如果一行包含两个单词,则列 斯塔纳姆只有2岁。我尝试了下面的代码,但得到结果的速度非常慢。数据有9万多行。 那么我该如何改进我的代码呢 import pandas as pd import numpy as np io=r'D:/test.xlsx' data1=pd.read_excel(io,sheet_name=0) data1['starnum']=0 l=le

我想判断每行是否包含一些特定的单词,如price、key、area等。如果一行包含其中一个单词,则starnum列将为1。如果一行包含两个单词,则列 斯塔纳姆只有2岁。我尝试了下面的代码,但得到结果的速度非常慢。数据有9万多行。 那么我该如何改进我的代码呢

import pandas as pd
import numpy as np

io=r'D:/test.xlsx'
data1=pd.read_excel(io,sheet_name=0)


data1['starnum']=0
l=len(data1)
print (l)

if data1['content'] is np.nan:
    data1['content']=''

data1['content']=data1['content'].str

for i in range(l):
    if data1.loc[i,'content'].find('price')>0:
        data1.loc[i,'starnum']+=1
for i in range(l):
    if data1.loc[i,'content'].find('area')>0:
        data1.loc[i,'starnum']+=1

for i in range(l):
    if data1.loc[i,'content'].find('key')>0:
        data1.loc[i,'starnum']+=1

print (data1)

您可以应用一个函数来获取
'content'
列的字符串,并对其中的子字符串进行计数,然后对计数进行求和

df['starnum'] = df.content.apply(lambda s: sum(s.count(t) for t in ['price', 'area', 'key']))

您没有使用
loc
手动循环,而是尝试了
data1['content']。应用了
?我尝试了这个方法,但没有成功。def函数:如果s.find('price')>0:返回1个数据1['starnum']=data1['content']。应用(函数)您希望
find
返回什么?我还没有见过类似的函数