Python 3.x 确定字符串中的字母数字模式

Python 3.x 确定字符串中的字母数字模式,python-3.x,pandas,dataframe,Python 3.x,Pandas,Dataframe,下面是有关df简化版本的脚本: import pandas as pd df = pd.DataFrame({ 'reg': ['AAA123', '456BBB','C7C8C9','DDDEEE01010'] }) df reg 0 AAA123 1 456BBB 2 C7C8C9 3 DDDEEE01010 我想创建一个列,表示每个reg值的字母数字模式,每个字母用'L',每个数字用'N' 请注

下面是有关df简化版本的脚本:

import pandas as pd

df = pd.DataFrame({ 
               'reg': ['AAA123', '456BBB','C7C8C9','DDDEEE01010']
                 })
df

    reg
0   AAA123
1   456BBB
2   C7C8C9
3   DDDEEE01010
我想创建一个列,表示每个reg值的字母数字模式,每个字母用
'L'
,每个数字用
'N'

请注意,reg的长度可能不同,并且具有随机数以及字母和数字的顺序

预期产出:

    reg          pattern
0   AAA123       LLLNNN
1   456BBB       NNNLLL
2   C7C8C9       LNLNLN
3   DDDEEE01010  LLLLLLNNNNN

非常感谢您的帮助。

使用
str.replace
我们可以尝试:

data["pattern"] = data["reg"].str.replace(r'[A-Z]', 'L')
                             .str.replace(r'[0-9]', 'N')

使用
str.replace
我们可以尝试:

data["pattern"] = data["reg"].str.replace(r'[A-Z]', 'L')
                             .str.replace(r'[0-9]', 'N')

您可以使用
replace
regex
选项:

df['pattern'] = df.reg.replace({'[a-zA-Z]':'L', '\d':'N'}, regex=True)
或者,如果您确定字符串只包含字母数字字符,则可以使用
\D
表示字母:

    df['pattern'] = df.reg.replace({'\D':'L', '\d':'N'}, regex=True)
输出:

           reg      pattern
0       AAA123       LLLNNN
1       456BBB       NNNLLL
2       C7C8C9       LNLNLN
3  DDDEEE01010  LLLLLLNNNNN

您可以使用
replace
regex
选项:

df['pattern'] = df.reg.replace({'[a-zA-Z]':'L', '\d':'N'}, regex=True)
或者,如果您确定字符串只包含字母数字字符,则可以使用
\D
表示字母:

    df['pattern'] = df.reg.replace({'\D':'L', '\d':'N'}, regex=True)
输出:

           reg      pattern
0       AAA123       LLLNNN
1       456BBB       NNNLLL
2       C7C8C9       LNLNLN
3  DDDEEE01010  LLLLLLNNNNN

@TimBiegeleisen它是
.replace
,而不是
.str.replace
.replace
允许传递字典。@TimBiegeleisen它是
.replace
,而不是
.str.replace
.replace
允许传递字典。