pandas应用regex替换值

2024-05-23 22:56:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我已将一些定价数据读入pandas数据框,其值显示为:

$40,000*
$40000 conditions attached

我想把它简化成数值。 我知道我可以循环使用regex

[0-9]+

然后将结果列表重新连接到每个字段,但是否有不循环的方法?

谢谢


Tags: 数据方法pandas列表conditionsregex数值定价
3条回答

您可以使用^{}

import pandas as pd

df = pd.DataFrame(['$40,000*','$40000 conditions attached'], columns=['P'])
print(df)
#                             P
# 0                    $40,000*
# 1  $40000 conditions attached

df['P'] = df['P'].str.replace(r'\D+', '').astype('int')
print(df)

收益率

       P
0  40000
1  40000

因为\D匹配任何non-decimal digit

您可以使用pandas的replace方法;还可以保留千位分隔符“,”和小数点分隔符“

import pandas as pd

df = pd.DataFrame(['$40,000.32*','$40000 conditions attached'], columns=['pricing'])
df['pricing'].replace(to_replace="\$([0-9,\.]+).*", value=r"\1", regex=True, inplace=True)
print(df)
pricing
0  40,000.32
1      40000

您可以使用re.sub()删除所有非数字:

value = re.sub(r"[^0-9]+", "", value)

regex101 demo

相关问题 更多 >