首页 > 解决方案 > 将数据框中的一列美元值转换为整数

问题描述

我有一个混合的美元值作为列中的字符串;有些带有 $ 和逗号,有些没有。如何将这些转换为整数值?这是一个示例。

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

标签: pythonpandas

解决方案


Series.replace与 convert to floats 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_numericwitherrors='coerce'处理缺失值:

df2.PRICE = pd.to_numeric(df2.PRICE.replace('[\$,]','', regex=True), errors='coerce')

推荐阅读