python - 将数据框中的一列美元值转换为整数
问题描述
我有一个混合的美元值作为列中的字符串;有些带有 $ 和逗号,有些没有。如何将这些转换为整数值?这是一个示例。
df2.PRICE
Out[193]:
0 $179,000.00
1 $110,000.00
2 $275,000.00
3 $140,000.00
4 $180,000.00
564611 85500
564612 80800
564613 74500
564614 75900
564615 66700
Name: PRICE, Length: 564616, dtype: object
解决方案
Series.replace
与 convert to float
s by一起使用Series.astype
:
df2.PRICE = df2.PRICE.replace('[\$,]','', regex=True).astype(float)
print (df2)
PRICE
0 179000.0
1 110000.0
2 275000.0
3 140000.0
4 180000.0
564611 85500.0
564612 80800.0
564613 74500.0
564614 75900.0
564615 66700.0
如果总是有integers
:
df2.PRICE = df2.PRICE.replace('[\$,]','', regex=True).astype(float).astype(int)
print (df2)
PRICE
0 179000
1 110000
2 275000
3 140000
4 180000
564611 85500
564612 80800
564613 74500
564614 75900
564615 66700
如果转换为浮点数失败,如果无法转换为数字,则使用to_numeric
witherrors='coerce'
处理缺失值:
df2.PRICE = pd.to_numeric(df2.PRICE.replace('[\$,]','', regex=True), errors='coerce')
推荐阅读
- python - ImportError:导入模块时DLL加载失败
- java - 在回收站视图中单独包装项目的内容?
- node.js - Mongoose 不解决回调查询?
- python - 有没有办法在不接收 python 中的 html 文件的情况下获取 HTTP 响应代码?
- reduce - DataWeave 2.0 如何为 reduce() 构建动态填充的累加器
- windows - Powershell:是否有编程方式来确定 Windows 10 上是否启用了通知?
- c# - 在服务中调用 JavaScript 函数
- java - 是否有必要在构造函数中同步块?
- ios - UIPageViewController 直接跳转到页面会导致实例变量出现问题
- java - ArrayDeque 的 Stack 和同步装饰器之间的区别