簡體   English   中英

使 Python 代碼更快處理 2400 萬條記錄

[英]Making python code faster for processing 24 million records

我正在嘗試處理熊貓數據框。 我正在將函數應用於其中一列。

功能是:

def separate_string(sentence):
    string_even = ""
    if sentence is not None:
        l = list(sentence)
        list_even = list()
        index = 0    
        for letter in l:
            if index % 2 != 0:
               if abs(ord(letter)-3) < 1114111:
                    list_even.append((chr(abs(ord(letter)-3))))
               string_even = "".join(list_even)
            index += 1
    return(str(string_even))

熊貓數據框:

df['re'] = df.col1.apply(separate_string)

我在帶有 64GB RAM 2.19Ghz 7 處理器的 PC 上運行它。 為什么代碼永遠不會完成?

如果我是你,我會嘗試使用Cython 來優化你的 Python 代碼。 從本質上講,這將使 C 代碼的運行速度(希望)快幾個數量級。

我認為這可以滿足您的要求。 如果需要,您可能必須明確返回None而不是空字符串。

刪除了很多東西,例如不需要的強制轉換和索引的手動維護以及代碼點小於 1114111 的測試,因為它們都將是。

def separate_string(sentence):
    return "".join(chr(abs(ord(letter) -3)) for letter in sentence[1::2])

我們可以timeit看看我們是否有改進:

import timeit

setup_orig = '''
test = "This eBook is for the use of anyone anywhere in the United States and most other parts of the world at no cost and with almost no restrictions whatsoever."
def separate_string(sentence):
    string_even = ""
    if sentence is not None:
        l = list(sentence)
        list_even = list()
        index = 0    
        for letter in l:
            if index % 2 != 0:
               if abs(ord(letter)-3) < 1114111:
                    list_even.append((chr(abs(ord(letter)-3))))
               string_even = "".join(list_even)
            index += 1
    return(str(string_even))
'''

setup_new = '''
test = "This eBook is for the use of anyone anywhere in the United States and most other parts of the world at no cost and with almost no restrictions whatsoever."
def separate_string(sentence):
    return "".join(chr(abs(ord(letter) -3)) for letter in sentence[1::2])
'''

print(timeit.timeit('separate_string(test)', setup=setup_orig, number=100_000))
print(timeit.timeit('separate_string(test)', setup=setup_new, number=100_000))

在我的筆記本電腦上,結果如下:

5.33
0.95

因此,作為解決方案的一部分,它似乎值得探索。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM