【问题标题】:Changing the value of elements in a series of a dataframe python更改一系列数据框python中元素的值
【发布时间】:2016-05-09 18:15:55
【问题描述】:

我想将读取为字符串的美元金额更改为浮点数。以下是数据框系列的摘录。我想去掉美元符号并将值转换为浮点数。最好的方法是什么?

0          $0 
1    $186,800 
2     $87,600 
3    $139,200 
4    $168,100 
Name: DemMedHomeValue, dtype: object
0         $0 
1         $0 
2    $38,750 
3    $38,942 
4    $71,509 
Name: DemMedIncome, dtype: object

【问题讨论】:

    标签: python pandas dataframe type-conversion series


    【解决方案1】:

    使用str.strip 删除$str.replaceastype 转换为float

    print df
      DemMedHomeValue
    0              $0
    1        $186,800
    2         $87,600
    3        $139,200
    4        $168,100
    
    df['DemMedHomeValue'] = df['DemMedHomeValue'].str.strip('$')
                                                 .str.replace(',', '.')
                                                 .astype(float)
    print df
       DemMedHomeValue
    0              0.0
    1            186.8
    2             87.6
    3            139.2
    4            168.1
    

    【讨论】:

      猜你喜欢
      • 2019-03-08
      • 2015-04-11
      • 2020-09-25
      • 2021-11-24
      • 2018-11-13
      • 2018-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多