apply a function on the columns from the list

Question:

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])
Asked By: lapots

||

Answers:

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)
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.