Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a variable amount of columns in python pandas apply

I am trying to add columns to a python pandas df using the apply function. However the number of columns to be added depend on the output of the function used in the apply function.

example code:

number_of_columns_to_be_added = 2    
def add_columns(number_of_columns_to_be_added):
         df['n1'],df['n2'] = zip(*df['input'].apply(lambda x : do_something(x, number_of_columns_to_be_added)))

Any idea on how to define the ugly column part (df['n1'], ..., df['n696969']) before the = zip( ... part programatically?

like image 655
Patty Avatar asked Dec 17 '25 13:12

Patty


1 Answers

I'm guessing that the output of zip is a tuple, therefore you could try this:

temp = zip(*df['input'].apply(lambda x : do_something(x, number_of_columns_to_be_added)))
for i, value in enumerate(temp, 1):
    key = 'n'+str(i)
    df[key] = value

temp will hold the all the entries and then you iterate over tempto assign the values to your dict with your specific keys. Hope this matches your original idea.

like image 52
Skandix Avatar answered Dec 20 '25 11:12

Skandix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!