How to determine a variable number of columns in python pandas apply

I am trying to add columns in python pandas df using the apply function. However, the number of columns to add depends on the output of the function used in the apply function.

code example:

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 programmatically identify the ugly column (df['n1'], ..., df['n696969'])part before the part = zip( ...?

+4
source share
1 answer

I assume the output zipis a tuple, so you can try the following:

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

tempwill hold all entries and then you are iterateover tempto assign values ​​to your dict using your specific keys. Hope this matches your original idea.

0
source

Source: https://habr.com/ru/post/1693530/


All Articles