Python - Applying a function to separate string in column every two words

Viewed 32

I want to add a separator (,) every two words capture/better delineate the full names of the row.

For example df['Names'] is currently: John Smith David Smith Golden Brown Austin James

and I would like to be:

John Smith, David Smith, Golden Brown, Austin James

I was able to find some code which splits the string every x words which would be perfect for my purposes shown below:

def splitText(string):
    words = string.split()
    grouped_words = [' '.join(words[i: i + 2]) for i in range(0, len(words), 2)]
    return grouped_words

However I'm not sure how to apply this to the column of choice.

I tried the following:

df['Names'].apply(splitText())

This gives me a missing positional argument.

Asking for any advice on either modifying the function or my application of it to a column dataframe. I'm pretty new to this stuff so any advice would be great!

Cheers

1 Answers

You can pass only function without ():

df['Names'].apply(splitText)

Working like using lambda function:

df['Names'].apply(lambda x: splitText(x))
Related