pandas用正则表达式替换值
我把一些价格数据读入了一个叫做pandas的数据框,里面的值看起来是这样的:
$40,000*
$40000 conditions attached
我想把这些值简化成只有数字。我知道我可以通过循环来处理每个字段,使用正则表达式
[0-9]+
然后把处理后的结果再合并回去,但有没有一种不需要循环的方法呢?
6 个回答
1
如果还有人看到这个,我正在处理一个类似的问题,需要用我用正则表达式(regex)写的公式来替换pandas数据中的整个列,使用的是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!
希望这能帮助到正在寻找我遇到的问题的朋友们。谢谢!
8
你不需要用正则表达式来解决这个问题。你可以这样做:
df['col'] = df['col'].astype(str).convert_objects(convert_numeric=True)
28
你可以使用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
155
你可以使用 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)
这样会得到
P
0 40000
1 40000
因为 \D
是用来匹配任何不是数字的字符。
21