python - 如何改进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
无论如何我可以改进它吗?
解决方案
使用 lambda 函数进行更通用的替换df[col].apply(lambda x: x.str.replace(',',''))
会更合适且更省时吗?
像这样的一个班轮不会产生你所追求的吗?
df['col'] = (df['col'] / 500).astype(int) * 500
推荐阅读
- reactjs - AppStructure - 将 useRef 对象从反应服务传递到组件
- javascript - PHP邮件功能不发送电子邮件
- java - 将学生分配到课程中
- ant - 常春藤依赖:log4j-api 已下载但未找到 log4j-api-java9
- vb.net - 调用 Click 事件在 Twitter 上不起作用:(
- c# - 将数据从 SQL Server 数据库导出到 Access 数据库
- scala - 为什么值不是 ArrayBuffer[Any] 中类的成员
- python - 烧瓶中的键错误
- excel - 开始声明变量以用于宏公式/格式化
- c# - 如何在 Blazor 中使用引导轮播