Get first list element in apply function Pandas


I have a function preprocess_names that splits an input variable:

def preprocess_names(name):
    return name.split('')

Also, I have a Pandas DataFrame df to which I want to apply this function.
In my case, the preprocess_names‘s output has length 3 and I want to use each value in a new column in df.

So, for the first new column, I want to use the first element from the output list. If I used this function on one str only, I would use preprocess_names[0] to get the correct variable. How can I do something similar while applying the method to df?

The code below raises ValueError, but is closest to what I would like to do.

df['runs'] = df['name'].apply(preprocess_names)[0]

>Solution :

Do you want:

df['runs'] = df['name'].apply(preprocess_names).str[0]

Leave a Reply Cancel reply