Open In App

Return multiple columns using Pandas apply() method

Last Updated : 08 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Objects passed to the pandas.apply() are Series objects whose index is either the DataFrame’s index (axis=0) or the DataFrame’s columns (axis=1). By default (result_type=None), the final return type is inferred from the return type of the applied function. Otherwise, it depends on the result_type argument.

Syntax:

s.apply(func, convert_dtype=True, args=())

Creating Dataframe to return multiple columns using apply() method

Python3




# Importing required Libraries
import pandas
import numpy
 
# Creating dataframe
dataFrame = pandas.DataFrame
        ([[4, 9], ] * 3, columns =['A', 'B'])
display(dataFrame)


Output:

 

Below are some programs which depict the use of pandas.DataFrame.apply() 

Example 1: 

Using a Numpy universal function (in this case the same as numpy.sqrt()). 

Python3




# Using pandas.DataFrame.apply() on the data frame
print('Returning multiple columns from Pandas apply()')
dataFrame.apply(numpy.sqrt)


Output:

Returning multiple columns from Pandas apply()
    
A   B
0    2.0    3.0
1    2.0    3.0
2    2.0    3.0

Example 2: 

Using a reducing function on columns. 

Python3




# Using pandas.DataFrame.apply() on the data frame
print('Returning multiple columns from Pandas apply()')
dataFrame.apply(numpy.sum, axis = 0)


Output:

Returning multiple columns from Pandas apply()
A    12
B    27
dtype: int64 

Example 3: 

Using a reducing function on rows. 

Python3




# Using pandas.DataFrame.apply() on the data frame
print('Returning multiple columns from Pandas apply()')
dataFrame.apply(numpy.sum, axis = 1)


Output:

Returning multiple columns from Pandas apply()
0    13
1    13
2    13
dtype: int64 

Example 4: 

Returning a list-like will result in a Series using the lambda function

Python3




# Using pandas.DataFrame.apply() on the data frame
print('Returning multiple columns from Pandas apply()')
dataFrame.apply(lambda x: [1, 2], axis = 1)


Output:

Returning multiple columns from Pandas apply()
0    [1, 2]
1    [1, 2]
2    [1, 2]
dtype: object 

Example 5: 

Passing result_type=’expand’ will expand list-like results to columns of a Dataframe. 

Python3




# Using pandas.DataFrame.apply() on the data frame
print('Returning multiple columns from Pandas apply()')
dataFrame.apply(lambda x: [1, 2], axis = 1, result_type ='expand')


Output:

Returning multiple columns from Pandas apply()
0    1
0    1    2
1    1    2
2    1    2 

Example 6: 

Returning a Series inside the function is similar to passing result_type=’expand’. The resulting column names will be the Series index. 

Python3




# Using pandas.DataFrame.apply() on the data frame
print('Returning multiple columns from Pandas apply()')
dataFrame.apply(lambda x: pandas.Series(
    [1, 2], index =['foo', 'bar']), axis = 1)


Output:

Returning multiple columns from Pandas apply()
foo    bar
0    1    2
1    1    2
2    1    2 

Example 7: 

Passing result_type=’broadcast’ will ensure the same shape result, whether list-like or scalar is returned by the function, and broadcasted along the axis. The resulting column names will be the originals.

Python3




# Using pandas.DataFrame.apply() on the data frame
print('Returning multiple columns from Pandas apply()')
dataFrame.apply(lambda x: [1, 2], axis = 1, result_type ='broadcast')


Output:

Returning multiple columns from Pandas apply()
A    B
0    1    2
1    1    2
2    1    2 


Similar Reads

How to Apply a function to multiple columns in Pandas?
Pandas.apply allow the users to pass a function and apply it on every single value of the Pandas series. Syntax of pandas.DataFrame.apply Syntax : DataFrame.apply(parameters) Parameters : func : Function to apply to each column or row.axis : Axis along which the function is appliedraw : Determines if row or column is passed as a Series or ndarray o
3 min read
Apply String Methods Across Multiple Columns in a Pandas DataFrame
We are given a dataframe in Pandas with multiple columns, and we want to apply string methods to transform the data within these columns. In this article, we will explore three different approaches to applying string methods to multiple columns of a dataframe. Apply String Methods to Multiple Columns of a DataframeBelow are the possible approaches
2 min read
Highlight Pandas DataFrame's specific columns using apply()
Let us see how to highlight specific columns of a Pandas DataFrame. We can do this using the apply() function of the Styler class. Styler.apply() Syntax : Styler.apply(func, axis = 0, subset = None, **kwargs) Parameters : func : function should take a Series or DataFrame (depending on-axis), and return an object with the same shape. Must return a D
2 min read
Apply a transformation to multiple columns PySpark dataframe
In this article, we are going to learn how to apply a transformation to multiple columns in a data frame using Pyspark in Python. The API which was introduced to support Spark and Python language and has features of Scikit-learn and Pandas libraries of Python is known as Pyspark. While using Pyspark, you might have felt the need to apply the same f
7 min read
Apply a function to single or selected columns or rows in Pandas Dataframe
In this article, we will learn different ways to apply a function to single or selected columns or rows in Dataframe. We will use Dataframe/series.apply() method to apply a function. Apply a function to single row in Pandas DataframeHere, we will use different methods to apply a function to single rows by using Pandas dataframe. First lets create a
5 min read
Using Apply in Pandas Lambda functions with multiple if statements
In this article, we are going to see how to apply multiple if statements with lambda function in a pandas dataframe. Sometimes in the real world, we will need to apply more than one conditional statement to a dataframe to prepare the data for better analysis. We normally use lambda functions to apply any condition on a dataframe, Syntax: lambda arg
3 min read
Partitioning by multiple columns in PySpark with columns in a list
Pyspark offers the users numerous functions to perform on the dataset. One such function which seems to be too useful is Pyspark, which operates on group of rows and return single value for every input. Do you know that you can even the partition the dataset through the Window function? Not only partitioning is possible through one column, but you
5 min read
Creating Pivot Table with Multiple Columns using Python Pandas
PythonPandas make data manipulation, representation and analysis easier. Pandas Pivot Tables are used to create spreadsheet-style pivot tables as a DataFrame. The levels in the pivot table will be stored in MultiIndex objects (hierarchical indexes) on the index and columns of the result DataFrame. Pivot Table with Multiple Columns using PandasA piv
4 min read
Combining multiple columns in Pandas groupby with dictionary
Let' see how to combine multiple columns in Pandas using groupby with dictionary with the help of different examples. Example #1: # importing pandas as pd import pandas as pd # Creating a dictionary d = {'id':['1', '2', '3'], 'Column 1.1':[14, 15, 16], 'Column 1.2':[10, 10, 10], 'Column 1.3':[1, 4, 5], 'Column 2.1':[1, 2, 3], 'Column 2.2':[10, 10,
2 min read
Collapse multiple Columns in Pandas
While operating dataframes in Pandas, we might encounter a situation to collapse the columns. Let it be cumulated data of multiple columns or collapse based on some other requirement. Let's see how to collapse multiple columns in Pandas. Following steps are to be followed to collapse multiple columns in Pandas: Step #1: Load numpy and Pandas. Step
2 min read