【问题标题】:how to improve for loop in python如何改进python中的for循环
【发布时间】:2020-08-06 14:56:27
【问题描述】:

我有这个代码:

    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

还有什么我可以改进的吗??

【问题讨论】:

标签: python pandas


【解决方案1】:

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

这样的单班轮会不会产生你所追求的东西?

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

【讨论】:

  • 指定col时不需要使用apply,可以使用df[col].str.replace(',','');)
【解决方案2】:

不要那样做for row in range(len(df[col])): 这样做:for row in df[col]

或者用这个代替那个:

用它来实际用另一个字符串替换字符串:DataFrame.replace

或更好地使用 lambda:DataFrame.apply (Example here)

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 2018-11-20
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 2017-01-06
    相关资源
    最近更新 更多