【发布时间】:2014-04-30 13:33:39
【问题描述】:
我已将一些定价数据读入 pandas 数据框中,这些值显示为:
$40,000*
$40000 conditions attached
我想将其简化为仅数值。 我知道我可以循环并应用正则表达式
[0-9]+
到每个字段,然后将结果列表重新连接在一起,但有没有一种不循环的方式?
谢谢
【问题讨论】:
我已将一些定价数据读入 pandas 数据框中,这些值显示为:
$40,000*
$40000 conditions attached
我想将其简化为仅数值。 我知道我可以循环并应用正则表达式
[0-9]+
到每个字段,然后将结果列表重新连接在一起,但有没有一种不循环的方式?
谢谢
【问题讨论】:
你可以使用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 匹配任何character that is not a decimal digit。
【讨论】:
万一有人还在读这篇文章。我正在处理一个类似的问题,需要使用我用 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!
希望这可以帮助任何搜索我遇到的问题的人。干杯
【讨论】:
rule2 = (lambda... 用作可调用对象,因此在您的obj.str.replace 中,正则表达式被传递匹配对象,即您的字典键以查找要替换的值对。阅读pandas.Series.str.replace 和dict.get() 了解更多信息。如果有人对m.group() 功能有任何澄清,请告诉我。
您可以使用 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
【讨论】:
您不需要正则表达式。这应该有效:
df['col'] = df['col'].astype(str).convert_objects(convert_numeric=True)
【讨论】:
【讨论】:
\D+ 将是最小的:-P