[英]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.