背景

使用pandas中的.str.replace()进行文本内容转变时,得到一个提醒FutureWarning: The default value of regex will change from True to False in a future version.。通过查阅,现将解决方式记录,以供未来再遇到时进行参考。

A u t h o r : S o p h e r Author: Sopher Author:Sopher
I d e n t i f i c a t i o n : S t u d e n t Identification: Student Identification:Student
D e s c r i p t i o n : Description: Description: 十年前种树是最好的时间,但现在也不晚!

过程说明

1.今天使用.str.replace()将表格数据中单价文本形式进行转化为Float过程中,遇到警告说明:FutureWarning: The default value of regex will change from True to False in a future version. pd_listings['price'] = pd_listings.price.str.replace(r"\$|,", '').astype(float)

2.原代码是这样的:

# 其中pd_listings是数据表装换为DataFrame
# price表示为价格特征
pd_listings['price'] = pd_listings.price.str.replace(r"\$|,", '').astype(float)

价格原数据格式:
在这里插入图片描述
价格转换后数据格式:
在这里插入图片描述

修改解释

  • 在Pandas未来的版本中,.str.replace()regex的默认值将从True变为False
  • 当regex=True时,单字符正则表达式不会被视为文本字符串
  • 因为我们是针对price中两个单个字符进行操作,因此设置regex=True

代码修改如下:

pd_listings['price'] = pd_listings.price.str.replace(r"\$|,", '',regex=True).astype(float)

此时,代码不会再出现警告

Q W Q , 继 续 坚 持 ! ! ! QWQ, 继续坚持!!! QWQ,

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐