[英]Improving performance of loops in python
我想不出另一种优化代码的方法。 我使用嵌套的for循环,我的计算机崩溃了。 所以我认为问题是我的代码。 我需要一些帮助。
我需要检查字符串列表(基本上是单词)是否在我df列的行中。 它需要遍历每一行并检查单词是否在其中。 我以为不会那么困难。 好吧,我错了。 我导入了excel文件。 共有3个。
filename='XXXX'
df = pd.read_excel(filename, sheetname='Data',index_col=0)`
df.columns:[['text', 'date', 'books', 'price']]
list_1 = ['apple', 'orange' , 'lime', 'pear']
list_2 = ['#loveapple', '#hateorange', '#likepear']
a = []
for word in df.text:
for fruit in list_1:
for tag in list_2:
if fruit in word:
fruit_list =fruit,word
elif tag in word:
tag_list = tag, word
all_data = [fruit_list,tag_list]
a.append(all_data)
TypeError:'in'需要字符串作为左操作数,而不是numpy.int64
(我过去运行过,但现在显示TypeError)
我已经阅读了一些帖子,但找不到通过整个列表的情况。 我发现的示例仅显示一个字符串,并且不适用于列表。 我也尝试了其他工具,例如xxx.str.contains
,但是没有用。
我把word
放了两次,所以我可以将word
的两个表合并。 但是,它会迭代超过35,000行,因此根本无法正常工作。 我需要先“过滤”数据,以便稍后进行分析。
提前致谢。
您可以在pandas列上使用apply方法。 编写一个执行所需比较的函数,然后将该函数应用于适当的列,例如:
def compare_string(s):
s = str(s) # This is necessary in case there are empty values in your Excel file.
list_1 = ['apple', 'orange' , 'lime', 'pear']
for fruit in list_1:
if fruit in s:
...
然后,您只需致电:
a = df.text.apply(compare_string)
如果您的Excel文件中有任何空值,它们将被读取为numpy.nan,其类型为numpy.int64。 这可能就是为什么您遇到类型错误的原因。 使用apply方法并将列中的每个元素转换为字符串应注意TypeError并提高代码的清晰度/性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.