2

I have a df of high schools. I'm trying to strip out the generic endings of the school's name.

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']

Desired:

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

4 Answers 4

4

Using split

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
Sign up to request clarification or add additional context in comments.

Comments

2
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

Comments

0

use rstrip()method to strip the undesired string from the rear of your original string. e.g.:

mystring = "Brown Academy"

mystring.rstrip("Academy") --> will give u the o/p: 'Brown '

Comments

0

I'd probably go with a regular expression substitution:

import re

df['school']=df['school'].apply(lambda x: re.sub(r'\s+((Academy)|(Prep)|(High)|(High School))$','',x))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.