python regex match and replace beginning and end of string but keep the middle

Viewed 9906

I have a dataframe with holiday names. I have a problem that on some days, holidays are observed on different days, sometimes on the day of another holiday. Here are some example problems:

1  "Independence Day (Observed)"
2  "Christmas Eve, Christmas Day (Observed)"
3  "New Year's Eve, New Year's Day (Observed)"
4  "Martin Luther King, Jr. Day"

I want to replace all ' (Observed)' with '' and everything before a comma only if ' (Observed)' is matched. Output should be:

1  "Independence Day"
2  "Christmas Day"
3  "New Year's Day"
4  "Martin Luther King, Jr. Day"

I was able to do both independently:

(foo['holiday']
 .replace(to_replace=' \(Observed\)', value='', regex=True)
 .replace(to_replace='.+, ', value='', regex=True))

but that caused a problem with 'Martin Luther King, Jr. Day'.

2 Answers
Related