如果长度小于x,则替换字符串

2024-09-27 18:17:25 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是一个数据帧。在

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

^{pr2}$

Tags: 数据方法文本iddataframe错误pdprint
1条回答
网友
1楼 · 发布于 2024-09-27 18:17:25

我认为您需要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

^{}的解决方案:

^{pr2}$

相关问题 更多 >

    热门问题