Extract sentences with capitalized words other than first word

Viewed 47

Say I have a dataframe

df = pd.DataFrame({'col1': ['Hello, world. Good day','My name is Bob. Call Me','good evening','yep. stack Overflow.',"Ain't McDonald Yo"]})

                      col1
0   Hello, world. Good day
1  My name is Bob. Call Me
2             good evening
3     yep. stack Overflow.
4        Ain't McDonald Yo

I'm trying to extract sentences from each row that contain capitalized words other than the first word. Sentences are separated by a period.

Output:

                      col1                     col2
0   Hello, world. Good day                      NaN
1  My name is Bob. Call Me  My name is Bob. Call Me
2             good evening                      NaN
3     yep. stack Overflow.           stack Overflow
4        Ain't McDonald Yo        Ain't McDonald Yo

1 Answers

Try:

df["col2"] = df["col1"].apply(
    lambda x: ".".join(
        [
            sentence
            for sentence in x.split(".")
            if any(word[0].isupper() for word in sentence.split()[1:])
        ]
    )
    or np.nan
)
print(df)

Prints:

                      col1                     col2
0   Hello, world. Good day                      NaN
1  My name is Bob. Call Me  My name is Bob. Call Me
2             good evening                      NaN
3     yep. stack Overflow.           stack Overflow
4        Ain't McDonald Yo        Ain't McDonald Yo
Related