How to Return Multiple Columns from Pandas using the Apply Function

Here is how you can return multiple pandas columns from an apply function.

def some_func(x):
  a = 1
  b = 2
  return a,b 

df[['column1','column2']] = df.apply(some_func,axis=1, result_type ='expand')

In your function, you can return multiple outputs by separating the list with a comma.

When you apply the function to your DataFrame, the key is to include this parameter to break up the output into multiple columns: result_type='expand'.

Finally, Using the double brackets, you can add the new columns to your DataFrame.

Final Thoughts

Check out more Python tricks in this Colab Notebook or in my recent Python Posts.

Thanks for reading!


Posted

in

by

Tags: