熊猫应用正则表达式替换值

我在一个熊猫数据框中读取了一些定价数据,数值显示如下:

$40,000*
$40000 conditions attached

我想把它分解成数值。 我知道我可以循环并应用正则表达式

[0-9]+

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

谢谢

137980 次浏览

You could remove all the non-digits using re.sub():

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

Regex101演示

You could use 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+', '', regex=True).astype('int')
print(df)

yields

       P
0  40000
1  40000

since \D matches any character that is not a decimal digit.

You don't need regex for this. This should work:

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

You could use pandas' replace method; also you may want to keep the thousands separator ',' and the decimal place separator '.'

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

In case anyone is still reading this. I'm working on a similar problem and need to replace an entire column of pandas data using a regex equation I've figured out with re.sub

To apply this on my entire column, here's the code.

#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!

Hope this helps anyone searching for the problem I had. Cheers