代码之家  ›  专栏  ›  技术社区  ›  spitfiredd

Pandas在字符串中搜索一个数字,并在其末尾返回字符?

  •  0
  • spitfiredd  · 技术社区  · 8 年前

    string_col
    541511N~541512N~541513N
    332710Y~332999Y
    Null
    238210Y~423690Y~517911Y~517919Y~532490Y~561421Y~811213Y
    

    我试图搜索某个数字,并得到最后的字符。

    541513 第一排是 541513N 我正在努力获得 N

    因此,我想创建一个包含这些信息的新专栏:

    string_col    541513_answer
    541511N~541512N~541513N    N
    332710Y~332999Y    NaN
    Null    Nan
    238210Y~423690Y~517911Y~517919Y~532490Y~561421Y~811213Y    Nan
    

    编辑:

    搜索“A6”并返回下一个8字符。

    string_col2    
    A620240328     
    A620180614     
    Null           
    xx     
    
    string_col2   x  
    A620240328    20240328
    A620180614    20180614
    Null          NaN
    xx            NaN
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   MaxU - stand with Ukraine    8 年前

    IIUC:

    In [35]: df['541513_answer'] = df.string_col.str.extract(r'541513(\w+)', expand=True)
    
    In [36]: df
    Out[36]:
                                              string_col 541513_answer
    0                            541511N~541512N~541513N             N
    1                                    332710Y~332999Y           NaN
    2                                               Null           NaN
    3  238210Y~423690Y~517911Y~517919Y~532490Y~561421...           NaN
    

    In [6]: df
    Out[6]:
      string_col2
    0  A620240328
    1  A620180614
    2        Null
    3          xx
    
    In [9]: df['x'] = df['string_col2'].str.extract(r'A6(.{8})', expand=False)
    
    In [10]: df
    Out[10]:
      string_col2         x
    0  A620240328  20240328
    1  A620180614  20180614
    2        Null       NaN
    3          xx       NaN
    
        2
  •  1
  •   Bill Bell    8 年前
    >>> df['54513_answer'] = df['string_col'].apply(lambda x: x[-1] if len(x)>6 and x[-7:-1]=='541513' else 'Null')
    >>> df
                                              string_col 54513_answer
    0                            541511N~541512N~541513N            N
    1                                    332710Y~332999Y         Null
    2                                               Null         Null
    3  238210Y~423690Y~517911Y~517919Y~532490Y~561421...         Null