mlenthusiast
mlenthusiast

Reputation: 1194

Apply function to a list of columns in a loop and output dataframe

I have a function that is set up like this:

def function(df, apply_col, static_col):
    do something
    return df

#calling the function
df = function(df, 'col_a', 'st_col')

This works fine. But, I want to apply this function to a list of columns by name. I tried something like this:

col_list = ['col_a', 'col_b', 'col_c'....'col_n']

for i in list:
    df = function(df, i, 'st_col')

I get a TypeError: 'list' object is not callable

I would like to apply this function to a dataframe in a loop with the static column staying the same and returning a resulting dataframe with all the columns having the function applied to them. Any ideas are appreciated!

Upvotes: 0

Views: 208

Answers (1)

itprorh66
itprorh66

Reputation: 3288

I think your issue is with the line for i in list: Since list is defined as a python object it should read for i in col_list:

Upvotes: 1

Related Questions