我正在使用包含字母,特殊字符和数字的数据框。我的目标是提取所有字母和第一个数字。所有数字总是出现在字母和特殊字符之后;但是,某些字母可能会出现在特殊字符之后。请参见下面的示例:
d = {'col1': ['A./B. 1234', 'CDEF/G5.','AB./C23']}
df = pd.DataFrame(data=d)
print(df)
# col1
# 0 A./B. 1234
# 1 CDEF/G5.
# 2 AB./C23
我查询了许多变体,但不知道如何处理特殊字符./
等。
df.col1.str.extract('([A-Za-z\d]+)')
# 0
# 0 A
# 1 CDEF
# 2 AB
这会给我所有字母和数字,直到达到特殊字符为止。最终,我希望得到以下输出:
AB1
CDEFG5
ABC2
我是正则表达式新手。
您需要提取所有字符,直到第一个数字,包括第一个数字,然后用空字符串替换所有非字母/数字字符:
d = {'col1': ['A./B. 1234', 'CDEF/G5.','AB./C23']}
df = pd.DataFrame(data=d)
df.col1.str.extract(r'^([^\d]+\d)').replace('[^A-Za-z0-9]', '', regex=True)
输出:
0
0 AB1
1 CDEFG5
2 ABC2
另一种方法
s=df['col1'].str.extractall("([a-zA-Z0-9])")[0]
s[s.str.isalpha()|s.shift().str.isalpha()].sum(level=0)
0 AB1
1 CDEFG5
2 ABC2
Name: 0, dtype: object
import re
#create compiled regex... just makes it easier
pat1 = re.compile(r'[a-z]+', flags=re.IGNORECASE)
pat2 = re.compile(r'\d{1}')
#extract words and numbers
step1 = [''.join(pat1.findall(entry)) for entry in df.col1]
step2 = [pat2.search(entry).group() for entry in df.col1]
#combine words and numbers, withe the number trailing word(s)
[''.join(ent) for ent in zip(step1,step2)]
['AB1', 'CDEFG5', 'ABC2']
每个字母后可以跟任意数量的特殊字符。之后,您得到一个数字。以下正则表达式对此进行编码:
((?:[A-Za-z][./\w]*)+\d)