尝试将Python Pandas中的字符串转换为Float时发生错误(Error when trying to convert a column with string in Python Panda

编程入门 行业动态 更新时间:2024-10-07 16:21:17
尝试将Python Pandas中的字符串转换为Float时发生错误(Error when trying to convert a column with string in Python Pandas to Float)

我有一个名为'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”,我会得到

ValueError: could not convert string to float: $5.41

所以我该怎么做?

I have a column named 'market_cap_(in_us_$)' which values are like:

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

My final goal is to be able to filter based on specific numeric values (for example, > 2000.00).

By reading other questions in this site, I followed the instructions as:

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

However, I receiving the following error

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

If I remove the "regex = True" from the replace arguments, I get

ValueError: could not convert string to float: $5.41

So, what should I do?

最满意答案

这里给出了正确使用的正则表达式,因为您想要移除$和:

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'错误,你必须使用一个非常旧的版本,并且应该更新。

The right regular expression to use is given here, as you want to remove the $ and ,:

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

But since you got that keyword argument 'regex' error, you must be using a very old version, and should update.

更多推荐

本文发布于:2023-08-07 13:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464136.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   字符串   发生错误   Python   Pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!