2

I have a dataframe with 3 columns

           Hospital              2009-10  2010-11
Aberystwyth Mental Health Unit     19       19
Bro Ddyfi Community Hospital       16       10  
Bronglais General Hospital         160      148
Caebryn Mental Health Unit         37       39 
Carmarthen Mental Health Unit      38       31  

I am trying to create a function that checks if a word is in the hospital column if so it puts the word in the new column like so:

               Hospital              2009-10  2010-11    Hospital Type
    Aberystwyth Mental Health Unit     19       19          Mental
    Bro Ddyfi Community Hospital       16       10          Community  
    Bronglais General Hospital         160      148         General
    Caebryn Mental Health Unit         37       39          Mental
    Carmarthen Mental Health Unit      38       31          Mental

Heres the code I have tried:

def find_type(x):
    if df['Hospital'].str.contains("Mental").any():
        return "Mental"
    if df['Hospital'].str.contains("Community").any():
        return "Community"
    else:
        return "Other"

df['Hospital Type'] = df.apply(find_type)

The output I get instead is this:

               Hospital              2009-10  2010-11    Hospital Type
    Aberystwyth Mental Health Unit     19       19          NaN
    Bro Ddyfi Community Hospital       16       10          NaN  
    Bronglais General Hospital         160      148         NaN
    Caebryn Mental Health Unit         37       39          NaN
    Carmarthen Mental Health Unit      38       31          NaN

How can I get it so it comes out like the expected output?

Thank you!

1 Answer 1

5

Use extract by keywords separated by | with fillna:

pat = r"(Mental|Community)"
df['Hospital Type'] = df['Hospital'].str.extract(pat, expand=False).fillna('Other')
print (df)
                         Hospital  2009-10  2010-11 Hospital Type
0  Aberystwyth Mental Health Unit       19       19        Mental
1    Bro Ddyfi Community Hospital       16       10     Community
2      Bronglais General Hospital      160      148         Other
3      Caebryn Mental Health Unit       37       39        Mental
4   Carmarthen Mental Health Unit       38       31        Mental
Sign up to request clarification or add additional context in comments.

1 Comment

@ScottBoston - thank you, but now it is not possible, because not 15 minutes after posting left ;)

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.