移除子字符串,python

2024-04-28 20:36:38 发布

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

我有很多高中。我想去掉学校名字的通用结尾。你知道吗

in[1]:df
out[2]:
     time    school
1    09:00   Brown Academy
2    10:00   Covfefe High School
3    11:00   Bradley High
4    12:00   Johnson Prep

school_endings = ['Academy','Prep,'High','High School']

期望值:

out[3]:
     time    school
1    09:00   Brown
2    10:00   Covfefe
3    11:00   Bradley
4    12:00   Johnson

Tags: intime结尾out名字学校highschool
3条回答

使用拆分

df.school = df.school.str.split(' ').str[0]

    school  time
0   Brown   09:00
1   Covfefe 10:00
2   Bradley 11:00
3   Johnson 12:00

使用rstrip()方法从原始字符串的后面去除不需要的字符串。 e、 g.:

mystring = "Brown Academy"

mystring.rstrip("Academy")-->;将给您o/p:'Brown'

endings = ['Academy', 'Prep', 'High', 'High School']

endings = sorted(endings, key=len, reverse=True)

df.assign(school=df.school.replace(endings, '', regex=True).str.strip())

    time   school
1  09:00    Brown
2  10:00  Covfefe
3  11:00  Bradley
4  12:00  Johnson

相关问题 更多 >