【问题标题】:How can I increase the amount of array iterated during the run-time of script?如何增加脚本运行时迭代的数组数量?
【发布时间】:2019-12-14 20:43:58
【问题描述】:

我的脚本从“@#$!”等不需要的字符串中清除数组和其他东西。 该脚本按预期工作,但是当 excel 行大小很大时,它的速度非常慢。

如果它可以加快速度,我尝试使用 numpy,但我不太熟悉它,所以我可能使用不正确。

xls = pd.ExcelFile(path)
df = xls.parse("Sheet2")

TeleNum = np.array(df['telephone'].values)

def replace(orignstr):  # removes the unwanted string from numbers
    for elem in badstr:
        if elem in orignstr:
            orignstr = orignstr.replace(elem, '')
    return orignstr


for UncleanNum in tqdm(TeleNum):
    newnum = replace(str(UncleanNum))  # calling replace function
    df['telephone'] = df['telephone'].replace(UncleanNum, newnum)  # store string back in data frame

我还尝试删除该方法,如果有帮助,只需将其作为一个代码块放置,但速度保持不变。

for UncleanNum in tqdm(TeleNum):
    orignstr = str(UncleanNum)
    for elem in badstr:
        if elem in orignstr:
            orignstr = orignstr.replace(elem, '')
            print(orignstr)
    df['telephone'] = df['telephone'].replace(UncleanNum, orignstr)
TeleNum = np.array(df['telephone'].values)

目前运行 200,000 个 excel 文件的脚本速度约为 70it/s,大约需要一个小时才能完成。这不是很好,因为这只是众多功能之一。

我在 python 方面不太先进。我只是在编写脚本时学习,如果您有任何指点,将不胜感激。

编辑:

我处理的大多数数组元素都是数字,但有些包含字符串。我试图删除数组元素中的所有字符串。

例如

FD3459002912
*345*9002912$

【问题讨论】:

    标签: python excel pandas numpy


    【解决方案1】:

    如果你想从字符串中清除所有不是数字的东西,你可以像这样直接使用 re.sub:

    import re
    
    string = "FD3459002912"
    regex_result = re.sub("\D", "", string)
    print(regex_result) # 3459002912
    

    【讨论】:

    • 谢谢,但这不是我想要的结果,但我不看正则表达式。
    • 从您的编辑中,我了解到您只想清除所有不是数字的内容,而不是替换任何内容。是这样吗?
    • 是的,如果数组元素中的char是字符串删除char,否则通过。
    • 为了说明我的脚本有效,我只想知道这是否是实现相同结果的更有效方法。
    • 是的,我知道。导致运行时间长的问题是 2 个嵌套的 for 循环,这就是我建议尝试其他方法的原因。如果您使用正则表达式 sub,您既可以找到所有不需要的字符,也可以替换它们,而无需使用 if 循环来加快处理速度。
    猜你喜欢
    • 2017-06-06
    • 2019-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 2015-08-15
    • 1970-01-01
    • 2011-05-06
    相关资源
    最近更新 更多