【问题标题】:finding +- 1 with regex python用正则表达式 python 查找 +- 1
【发布时间】:2021-09-12 19:47:34
【问题描述】:
我有一张这样的桌子:
name ...
0 AB1
1 AB2
2 AB3
3 AB4
5 CD1
...
... AB99
...
我想匹配前 2 个字母相同且数字相差 +- 1 的行。但是,最小的数字是 1,最大的数字是 99。
如何用正则表达式做到这一点?
示例:
- 如果我想要 AB1 的结果,我应该只得到 AB2
- 如果我想要 AB3 的结果,我应该得到 AB2 和 AB4
【问题讨论】:
标签:
python-3.x
regex
pandas
【解决方案1】:
您可以先提取数字并转换dtype:
# I am not v.good with regex so may be this part can be done better but idea is below
u = (df['name'].str.extract('(?P<name1>\D+)(?P<Num>\d+)').astype({"Num":int})
.join(df[['name']]).sort_values(['name1','Num']))
print(u)
name1 Num name
0 AB 1 AB1
1 AB 2 AB2
2 AB 3 AB3
3 AB 4 AB4
5 CD 1 CD1
一旦这个数据框准备好了,你就可以使用 shift 添加一个 pandas 函数:
def fun(inp,dataframe):
c = dataframe['name'].eq(inp)
g = dataframe.loc[c,'name1']
v = dataframe[dataframe['name1'].isin(g)]
c1 = (c.shift()|c.shift(-1))
return v.loc[c1,'name']
样本运行:
print(fun('AB1',u))
print("----------------")
print(fun("AB3",u))
1 AB2
Name: name, dtype: object
----------------
1 AB2
3 AB4
Name: name, dtype: object