Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get first list element in apply function Pandas

I have a function preprocess_names that splits an input variable:

def preprocess_names(name):
    #SOME PREPROCESSING
    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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading