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

Pandas function only works on individual columns but not entire dataframe

I have a dataframe like the following (example data given):

df = pd.DataFrame({'smiles': ['CCCCC', 'CCCC1', 'CCCN1'],
                        'ID' : ['A-111', 'A112', 'A-113'],
              'Parameter_1':[30.0, 31.4, 15.9],
              'Parameter_2':[NaN, '0.644', '4.38E-02'],
              'Date': [dt.date(2021, 1, 1), dt.date(2021, 1, 2), dt.date(2021, 1, 3)]})

I have the following function:

def num_parse(element):
    try:
        float(element)
        return float(element)
    except ValueError:
        return(element)
    except TypeError:
        return(element)

When I apply my function to individual columns it works fine – converting any string that can be floated into a float and leaving all other strings as is and also leaving the datetime column as is.

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

df['Parameter_1'] = df['Parameter_1'].apply(num_parse)

When I apply this to my entire dataframe I keep getting the following error:

df = df.apply(num_parse)

TypeError: cannot convert the series to <class ‘float’>

I am unsure why, please help.

>Solution :

Use applymap()

df.applymap(num_parse)

You could also:

df.apply(num_parse, axis=1)
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