apply a function on the columns from the list

I have a list of columns, whose values in the dataframe I want to convert to Decimal

column_list = ['Parameter 1', 'Parameter 2' ... 'Parameter N']

The data in a dataframe looks like this

Name | Parameter 1 | Parameter 2 | Surname | ... | Parameter N | ...

How to achieve that? If it I had a limited set of column names I could probably do something like df['Parameter 1'] = df['Parameter 1'].apply or something or maybe even with lambda row: ... etc.

But I am not sure how to achieve that if I have a list of columns that I want to update. Should I just iterate over the items like this for example?

for column_name in column_list:
    df[column_name] = Decimal(df[column_name])

>Solution :

Decimal needs to be applied on each individual value, so you must use applymap:

df[column_list] = df[column_list].applymap(Decimal)

Or with your loop:

for column_name in column_list:
    df[column_name] = df[column_name].apply(Decimal)

Leave a Reply