【问题标题】:Pandas String Series, return string if length equals number, otherwise return empty stringPandas 字符串系列,如果长度等于数字则返回字符串,否则返回空字符串
【发布时间】:2023-01-26 00:56:45
【问题描述】:

我有一个 Pandas 字符串系列如下:

s = pd.Series(["12345678.0","45678912.0", "0", "2983129416.0", "62441626.0"])

我首先必须去掉小数部分,然后......

result = s.str.split(".", 1, expand=True)[0]

如果长度为 8,我想找到一种返回字符串的方法,否则返回空字符串:""

s[s.str.len() == 8]

当然,这只会保留长度为 8 的字符串,但我需要将空字符串添加到长度不是 8 个字符的字段中。我无法自己弄清楚应该如何正确完成,所以提前感谢所有想法!

预期结果:

s = pd.Series(["12345678","45678912", "", "", "62441626"])

【问题讨论】:

    标签: python pandas string conditional-statements series


    【解决方案1】:
    import pandas as pd
    import numpy as np
    
    s = pd.Series(["12345678.0","45678912.0", "0", "2983129416.0", "62441626.0"])
    
    # Cut the decimal part
    result = s.str.split(".", 1, expand=True)[0]
    
    # Use np.where() to return a new series with the desired output
    result = np.where(result.str.len() == 8, result, '')
    
    #or 
    
    #result = result.apply(lambda x: x if len(x) == 8 else "")
    
    print(result)
    

    【讨论】:

      【解决方案2】:

      可以使用正则表达式:搜索从字符串开头到结尾长度为8位的字符串(忽略.之后的部分):

      print( s.str.extract(r'^(d{8})(?:.d+)?$').fillna('') )
      

      印刷:

                0
      0  12345678
      1  45678912
      2          
      3          
      4  62441626
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-31
        • 2014-10-30
        • 2020-05-11
        • 1970-01-01
        • 2013-12-11
        • 2023-03-07
        相关资源
        最近更新 更多