Replace string if length is less than x

I have an info frame 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 add text ('-s') to everything that is 4 characters long. I tried unsuccessfully below. since it causes an error, ValueError: the value of the series truth is ambiguous. Use the a.empty, a.bool (), a.item (), a.any (), or a.all () commands.

 if a['Id'].str.len() == 3: a['Id'] = a['Id'].str.replace('s', '-s') else: pass 
+5
source share
1 answer

I think you need loc , if you need to replace the last s , you need to 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 
+5
source

Source: https://habr.com/ru/post/1264026/


All Articles