replace string if length is less than x

旧巷老猫 提交于 2019-12-10 13:29:17

问题


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)

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

回答1:


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

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


来源:https://stackoverflow.com/questions/42140060/replace-string-if-length-is-less-than-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!