Reputation: 6475
I have a function which returns a tuple with two elements in python. I'm going to use this function to create two new columns in my dataframe in pandas. This is the code I have now
df['A','B'] = df.apply(lambda x: my_fun (X['A'], x['B'], other_arguments)[0:2], axis=1)
my_fun
returns tuples with 5 elements and I'm taking the first two elements to create the new columns.
However it creates only one column and set the value of that column to the tuple that my_fun
returns. How can I create two columns instead of one?
Upvotes: 1
Views: 676
Reputation: 7338
Try
df['A'], df['B'] = df.apply(lambda x: my_fun(x['A'], x['B'], other_arguments)[:2], axis=1)
if my_fun
returns a tuple with 5 elements and you only want to keep the first 2, then use a slice with the function call [:2]
Upvotes: 1
Reputation: 3770
df[['A','B']] = df.apply(lambda x: my_fun (X['A'], x['B'], other_arguments)[0:2], axis=1).apply(pd.Series)
Upvotes: 1