如果length小于x,则替换string

ben*_*121 6 python string replace conditional-statements pandas

我有一个数据框如下.

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)
Run Code Online (Sandbox Code Playgroud)

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

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

jez*_*ael 5

我认为你需要loc,如果需要替换最后s是必要的补充$:

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
Run Code Online (Sandbox Code Playgroud)

解决方案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
Run Code Online (Sandbox Code Playgroud)