【问题标题】:Python replace string with empty if length not equal to x如果长度不等于 x,Python 将字符串替换为空
【发布时间】:2019-10-01 22:59:33
【问题描述】:

我有以下数据框:

df=pd.DataFrame({'ssn':[12345,54321,111,47895,222311],'Name':['john','mike','adam','doug','liz']})

DataFrame 包含一个“ssn”,它应该只包含 5 位数字。我想用空格替换所有包含小于或大于 5 位数字的行。

想要的输出如下:

   Name   ssn
0  john   12345
1  mike   54321
2  adam   
3  doug   47895
4  liz    

我参考了 SO replace string if length is less than x 的以下帖子 但是,使用以下命令的相同解决方案会给我一个错误:

mask = df['ssn'].str.len() == 5
df['ssn'] = df['ssn'].mask(mask, df['ssn'].str.replace(df['ssn'], ''))
Traceback (most recent call last): 
TypeError: 'Series' objects are mutable, thus they cannot be hashed

如果有任何建议,我将不胜感激。

【问题讨论】:

  • df.assign(ssn=df.ssn.where(df.ssn.astype(str).str.len().eq(5), ''))。你没有处理字符串,所以我很惊讶你得到了那个错误,因为当你尝试使用字符串访问器时它应该出错
  • 效果很好!我如何接受你的回答?

标签: python dataframe replace string-length


【解决方案1】:

您也可以使用df.apply 执行此操作:df['ssn'] = df['ssn'].apply(lambda a: a if len(str(a))==5 else '')

【讨论】:

    【解决方案2】:

    您的列 ssn 包含数字而不是字符串,这就是它不起作用的原因。请尝试以下操作:

    mask = df['ssn'].astype(str).str.len() != 5
    df.loc[mask, 'ssn'] = ''
    
    In [1] : print(df)
    Out[1] :    Name    ssn
    0  john  12345
    1  mike  54321
    2  adam       
    3  doug  47895
    4   liz      
    

    【讨论】:

      猜你喜欢
      • 2017-06-27
      • 2012-09-15
      • 2015-06-17
      • 2012-04-28
      • 1970-01-01
      • 2014-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多