首页 > 解决方案 > 如何改进python中的for循环

问题描述

我有这个代码:

    for row in range(len(df[col])):
        df[col][row] = int(df[col][row].replace(',','')) 
    df[col] = df[col].astype(int)
    df[col] = np.round(df[col]/500)*500  #rounds the numbers to the closest 500 multiple.
    df[col] = df[col].astype(int) #round returns a float, this turns it back to int after rounding  

在 for 循环中: df[col][row].replace(',','') 基本上从存储为对象的数字中删除逗号,例如 1,430,然后将其转换为 int,例如 1430

然后我必须添加 df[col] = df[col].astype(int) 因为否则,以下 np.round() 会引发错误:'float' object has no attribute 'rint'

问题是,在 np.round() 之后,我必须再次添加 .astype(int) 因为我拥有的回合返回一个浮点数,但我想要整数。

我看到它的执行时间相当长,即使我的数据框只有 32 x 17

无论如何我可以改进它吗?

标签: pythonpandas

解决方案


使用 lambda 函数进行更通用的替换df[col].apply(lambda x: x.str.replace(',',''))会更合适且更省时吗?

像这样的一个班轮不会产生你所追求的吗?

df['col'] = (df['col'] / 500).astype(int) * 500


推荐阅读