【问题标题】:Extract Letters and the first Digit only仅提取字母和第一个数字
【发布时间】:2020-08-19 14:12:28
【问题描述】:

我正在处理一个包含字母、特殊字符和数字的数据框。我的目标是提取所有字母和第一个数字。所有数字总是出现在字母和特殊字符之后;但是,某些字母可能会出现在特殊字符之后。请看下面的例子:

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

我是正则表达式的新手。

【问题讨论】:

    标签: python regex pandas


    【解决方案1】:

    您需要提取直到第一个数字(包括第一个数字)的所有字符,然后将任何非字母/数字字符替换为空字符串:

    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
    

    【讨论】:

      【解决方案2】:

      另一种方法

      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
      

      【讨论】:

        【解决方案3】:
        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']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-11-04
          • 1970-01-01
          • 1970-01-01
          • 2015-05-24
          • 2015-05-14
          • 2022-06-15
          • 2018-06-27
          相关资源
          最近更新 更多