[英]Pandas replace string to Float
I want to remove the "HKD $" and change to Float object我想删除“HKD $”并更改为Float object
I use below command line but it doesnt work.我使用下面的命令行,但它不起作用。
df['price_list_1'] = df['price_list_1'].str.replace("HKD $","")
The result:结果:
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:1: FutureWarning: The default value of regex will change from True to False in a future version.
"""Entry point for launching an IPython kernel.
0 $14
1 $20
2 $55
3 $20
4 $50
...
647 $58
648 $20
649 $46
650 $70
651 $70
Name: price_list_1, Length: 652, dtype: object
When you use .str.replace()
, you should be care that if the string value includes any special characters of regular expressions such as $
, ^
, and *
, in this case, $
.使用
.str.replace()
时,应注意字符串值是否包含正则表达式的任何特殊字符,例如$
、 ^
和*
,在本例中$
。
To explicity say '$' is not for regular expression, you can use regex=False
.要明确地说 '$' 不适用于正则表达式,您可以使用
regex=False
。
df['price_list_1'] = df['price_list_1'].str.replace("HKD $","", regex=False)
For your information about using regular expression in str.replace
: see https://datascientyst.com/replace-values-regex-pandas/有关在 str.replace 中使用正则表达式的信息:请参阅
str.replace
://datascientyst.com/replace-values-regex-pandas/
You could also use str.lstrip
:您还可以使用
str.lstrip
:
out = df['price_list'].str.lstrip('$').astype(float)
Output: Output:
0 14.0
1 20.0
2 55.0
3 20.0
4 50.0
647 58.0
648 20.0
649 46.0
650 70.0
651 70.0
Name: price_list, dtype: float64
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.