Pandas apply() Return Multiple Columns

  • Post author:
  • Post category:Pandas / Python
  • Post last modified:January 21, 2023
Spread the love

In this article, I will explain how to return multiple columns from the pandas apply() function.

1. Quick Examples


# Example 1 - Reurn multiple columns from apply()
def multiply(row):
   row['A1'] = row[0] * 2
   row['B1'] = row[1] * 3
   row['C1'] = row[2] * 4
   return row

df = df.apply(multiply, axis=1)
print(df)

Let’s create a sample DataFrame to work with some examples.


import pandas as pd
import numpy as np
data = [(3,5,7), (2,4,6),(5,8,9)]
df = pd.DataFrame(data, columns = ['A','B','C'])
print(df)

Yields below output.


   A  B  C
0  3  5  7
1  2  4  6
2  5  8  9

2. Return Multiple Columns from pandas apply()

You can return a Series from the apply() function that contains the new data. pass axis=1 to the apply() function which applies the function multiply to each row of the DataFrame, Returns a series of multiple columns from pandas apply() function. This series, row, contains the new values, as well as the original data.


# Reurn multiple columns from apply()
def multiply(row):
   row['A1'] = row[0] * 2
   row['B1'] = row[1] * 3
   row['C1'] = row[2] * 4
   return row

df = df.apply(multiply, axis=1)
print(df)

Yields below output. This returns multiple columns ‘A1’, ‘B1’ and ‘C1’ from pandas apply() function.


   A  B  C  A1  B1  C1
0  3  5  7   6  15  28
1  2  4  6   4  12  24
2  5  8  9  10  24  36

Happy Learning !!

Leave a Reply

You are currently viewing Pandas apply() Return Multiple Columns