如果长度小于x则替换字符串 [英] replace string if length is less than x

查看:55
本文介绍了如果长度小于x则替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面有一个数据框.

I have a dataframe below.

a = {'Id': ['ants', 'bees', 'cows', 'snakes', 'horses'], '2nd Attempts': [10, 12, 15, 14, 0],
     '3rd Attempts': [10, 10, 9, 11, 10]}
a = pd.DataFrame(a)
print (a)

我希望能够将文本('-s')添加到等于4个字符的任何内容.我没有成功尝试以下.因为它会产生错误,所以ValueError:系列的真值不明确.使用a.empty,a.bool(),a.item(),a.any()或a.all().

I want to able add text ('-s') to anything which is equal to 4 characters. i have unsuccessfully tried the below. as it produces the error, ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

if a['Id'].str.len() == 3:
    a['Id'] = a['Id'].str.replace('s', '-s')
else:
    pass

推荐答案

我认为您需要loc,如果需要替换最后一个s,则必须添加$:

I think you need loc, if need replace last s is necessary add $:

mask = a['Id'].str.len() == 4
a.loc[mask, 'Id'] = a.loc[mask, 'Id'].str.replace('s$', '-s')
print (a)
   2nd Attempts  3rd Attempts      Id
0            10            10   ant-s
1            12            10   bee-s
2            15             9   cow-s
3            14            11  snakes
4             0            10  horses

使用 mask 的解决方案:

Solution with mask:

mask = a['Id'].str.len() == 4
a.Id = a.Id.mask(mask, a.Id.str.replace('s$', '-s'))
print (a)
   2nd Attempts  3rd Attempts      Id
0            10            10   ant-s
1            12            10   bee-s
2            15             9   cow-s
3            14            11  snakes
4             0            10  horses

这篇关于如果长度小于x则替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆