【发布时间】: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
还有什么我可以改进的吗??
【问题讨论】:
-
嗨,欢迎来到 SO,请参阅 How to Ask 和 minimal reproducible example - 你也不需要循环 -
df[col].replace(',','').astype(int)但不确定你要完全尝试什么 -
这能回答你的问题吗? Convert Pandas Dataframe to Float with commas and negative numbers,然后就用
astype(int)