如果length小于x,则替换string

时间:2017-02-09 15:02:11

标签: python string pandas replace conditional-statements

我有一个数据框如下。

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()。

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

1 个答案:

答案 0 :(得分: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

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
相关问题