Pandas apply() Return Multiple Columns

  • Post author:
  • Post category:Pandas
  • Post last modified:October 5, 2023

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.


# 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.


# Output:
   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 !!

Naveen

I am a Data Engineer with 20+ years of experience in transforming data into actionable insights. Over the years, I have honed my expertise in designing, implementing, and maintaining data pipelines with frameworks like Apache Spark, PySpark, Pandas, R, Hive and Machine Learning. My journey in the field of data engineering has been a continuous learning, innovation, and a strong commitment to data integrity. I have started this SparkByExamples.com to share my experiences with the data as I come across. You can learn more about me at LinkedIn

Leave a Reply

You are currently viewing Pandas apply() Return Multiple Columns