Applying lambda to variable number of columns

Viewed 43

I am trying to implement something in Python and I am stuck.

I have 2 dataframes, df1 and df2. I have to create a new column in df1 using the following logic.

col_list = ['colA', 'colB', 'colC']
df1['label_id'] = df1[['colA', 'colB', 'colC']].apply(
            lambda x: df2[x[0], x[1], x[2]], axis=1)

Here, x[0] corresponds to colA, x[1] corresponds to colB, x[2] corresponds to colC. As you can see, this is hardcoding. The number and names of columns in col_list will vary, and accordingly I should have x[0], x[1], x[2], x[3]... and so on.

So how do I make this configurable in implementation?

Appreciate any help. Thanks in advance.

0 Answers
Related