Python 替换行值
我想替换包含特定字符串的行中的值Python 替换行值,python,pandas,Python,Pandas,我想替换包含特定字符串的行中的值 center 1 /foo/2019 2 /foo/2020 3 /foo/3020 4 /foo/1000 5 900 6 /foo/189098 我想去掉字符串(在本例中是/foo/)。我怎样才能摆脱它们,从而得到这个结果 center 1 2019 2 2020 3 3020 4 1000 5 900 6 189098 谢谢 只是spli
center
1 /foo/2019
2 /foo/2020
3 /foo/3020
4 /foo/1000
5 900
6 /foo/189098
我想去掉字符串(在本例中是/foo/
)。我怎样才能摆脱它们,从而得到这个结果
center
1 2019
2 2020
3 3020
4 1000
5 900
6 189098
谢谢 只是
split
df.center.str.split('/').str[-1]
1 2019
2 2020
3 3020
4 1000
5 900
6 189098
Name: center, dtype: object
或lstrip
df.center.str.lstrip('/foo/')
1 2019
2 2020
3 3020
4 1000
5 900
6 189098
Name: center, dtype: object
或findall
df.center.str.findall('\d+').str[0]
1 2019
2 2020
3 3020
4 1000
5 900
6 189098
Name: center, dtype: object
或者我们可以使用:
有一个函数被指定为替换字符串:
df.center = df.center.str.replace('/foo/', '')
它也可以包含
regex
参数,但在您的情况下不需要它。这里解决的同一类型问题,如第1~4行,它包含多个/
,因此我猜第一个答案这次不起作用?然后使用findall
solution@jayko03,它从字符串中提取数字。@jayko03它将用于,因为我将最后一个.str[-1]
df.center = df.center.str.replace('/foo/', '')