应用正则表达式替换值的pandas

时间:2014-03-23 07:48:50

标签: python regex pandas

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

$40,000*
$40000 conditions attached

我想将其剥离为数值。 我知道我可以循环并应用正则表达式

[0-9]+

到每个字段然后将结果列表重新加入,但是有一种不循环的方式吗?

由于

5 个答案:

答案 0 :(得分:74)

您可以使用Series.str.replace

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匹配。

答案 1 :(得分:12)

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

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

regex101 demo

答案 2 :(得分:12)

你可以使用pandas的替换方法;你也可以保留千位分隔符','和小数位分隔符'。'

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

答案 3 :(得分:6)

你不需要正则表达式。这应该有效:

df['col'] = df['col'].astype(str).convert_objects(convert_numeric=True)

答案 4 :(得分:1)

万一有人还在读这个。我正在处理类似的问题,需要使用我用 re.sub 计算出的正则表达式来替换整列熊猫数据

要将其应用于我的整个专栏,这是代码。

#add_map is rules of replacement for the strings in pd df.
add_map = dict([
    ("AV", "Avenue"),
    ("BV", "Boulevard"),
    ("BP", "Bypass"), 
    ("BY", "Bypass"),
    ("CL", "Circle"),
    ("DR", "Drive"),
    ("LA", "Lane"),
    ("PY", "Parkway"),
    ("RD", "Road"),
    ("ST", "Street"),
    ("WY", "Way"),
    ("TR", "Trail"),
    
      
])

obj = data_909['Address'].copy() #data_909['Address'] contains the original address'
for k,v in add_map.items(): #based on the rules in the dict
    rule1 = (r"(\b)(%s)(\b)" % k) #replace the k only if they're alone (lookup \
b)
    rule2 = (lambda m: add_map.get(m.group(), m.group())) #found this online, no idea wtf this does but it works
    obj = obj.str.replace(rule1, rule2, regex=True, flags=re.IGNORECASE) #use flags here to avoid the dictionary iteration problem
data_909['Address_n'] = obj #store it! 

希望这可以帮助任何寻找我遇到的问题的人。干杯