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.

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)

Leave a Reply