【问题标题】:Error when trying to convert a column with string in Python Pandas to Float尝试将 Python Pandas 中带有字符串的列转换为浮点数时出错
【发布时间】:2014-08-03 12:57:43
【问题描述】:

我有一个名为“market_cap_(in_us_$)”的列,其值如下:

$5.41 
$18,160.50 
$9,038.20 
$8,614.30 
$368.50 
$2,603.80 
$6,701.50 
$8,942.40 

我的最终目标是能够根据特定的数值进行过滤(例如,> 2000.00)。

通过阅读本网站中的其他问题,我按照以下说明进行操作:

cleaned_data['market_cap_(in_us_$)'].replace( '$', '', regex = True ).astype(float)

但是,我收到以下错误

TypeError: replace() got an unexpected keyword argument 'regex'

如果我从替换参数中删除“regex = True”,我会得到 ​​p>

ValueError: could not convert string to float: $5.41

那么,我该怎么办?

【问题讨论】:

  • 您运行的是哪个版本的pandas? (print pd.__version__)
  • 我有 0.11.0,根据您的建议,我将其更新为 0.14.0。谢谢。

标签: python regex python-2.7 pandas


【解决方案1】:

问题在于$ 是正则表达式中的一个特殊字符,表示字符串的开头,因此仅替换字符串的开头最终不会替换任何内容!

您必须在系列上使用str.replace(使用文字 $ 和 ,):

In [11]: s.replace('\$|,', '', regex=True)
Out[11]:
0        5.41
1    18160.50
2     9038.20
3     8614.30
4      368.50
5     2603.80
6     6701.50
7     8942.40
dtype: object

In [12]: s.replace('\$|,', '', regex=True).astype('float64')
Out[12]:
0        5.41
1    18160.50
2     9038.20
3     8614.30
4      368.50
5     2603.80
6     6701.50
7     8942.40
dtype: float64

您可能想使用整美分而不是浮动美元(删除文字 .):

In [13]: s.replace('\$|,|\.', '', regex=True).astype('int64')
Out[13]:
0        541
1    1816050
2     903820
3     861430
4      36850
5     260380
6     670150
7     894240
dtype: int64

【讨论】:

    【解决方案2】:

    此处给出了要使用的正确正则表达式,因为您要删除 $,

    In [7]:
    
    df['market_cap_(in_us_$)'].replace('[\$,]', '', regex=True).astype(float)
    Out[7]:
    0        5.41
    1    18160.50
    2     9038.20
    3     8614.30
    4      368.50
    5     2603.80
    6     6701.50
    7     8942.40
    Name: market_cap_(in_us_$), dtype: float64
    

    但既然您收到了keyword argument 'regex' 错误,那么您肯定使用的是非常旧的版本,应该更新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-06
      • 1970-01-01
      • 2017-01-29
      • 1970-01-01
      • 2019-04-15
      • 2017-11-29
      • 2022-01-10
      相关资源
      最近更新 更多