【发布时间】:2021-07-14 10:52:19
【问题描述】:
在熊猫数据框中,我的行内容格式如下:
1) abc123-Target 4-ufs
2) abc123-target4-ufs
3) geo.4
4) j123T4
所有这些都应该是:目标 4
到目前为止,我的清洁程序如下:
df["point_id"] = df["point_id"].str.lower()
df["point_id"] = df['point_id'].str.replace('^.*?(?=target)', '')
这会返回:
1) target 4-ufs
2) target4-ufs
3) geo.14
4) geo.2
5) j123T4
我认为我需要的是:
a. Remove anything after the last number in the string, this solves 1
b. If 'target' does not have a space after it add a space, this with the above solves 2
c. If the string ends in a point and a number of any length remove everything before the point (incl. point) and replace with 'target ', this solves 3 and 4
d. If the string ends with a 't' followed by a number of any length remove everything before 't' and replace with 'target ', this solves 5
我正在查看 regex 和 re 但以下内容无效(在最后一个数字前添加空格)
df["point_id"] = re.sub(r'\D+$', '', df["point_id"])
【问题讨论】:
标签: python-3.x regex python-re