• Home
  • Insurance
  • Banking
  • Loans
  • Remitance
  • About us
Facebook Twitter Instagram
  • links
Biz Assurance
Subscribe
  • Home
  • Insurance
  • Banking
  • Loans
  • Remitance
  • About us
Biz Assurance
Home»Tech»Pandas Apply() Function to Every Row
Tech

Pandas Apply() Function to Every Row

Alicia CormieBy Alicia CormieNo Comments9 Mins Read
Facebook Twitter WhatsApp
Share
Facebook Twitter LinkedIn WhatsApp
Pandas provides many functions that make it easy to analyze and manipulate the data. We utilize those functions to make our tasks easier and quicker. We apply the functions to the rows and columns. To apply the function to each row in a specified “pandas” DataFrame, we utilize the apply() method. When we need to invoke any function to update each row in a “pandas” DataFrame, we utilize the “apply()” function. You should set the axis=1 variable to put a function to every row () in the “pandas” DataFrame. We utilize the “apply()” function in “pandas” in this guide with four unique methods using Series, Custom functions, NumPy and Lambda expressions.

Syntax:

DataFrame_object.apply(func, axis=0, raw=False, result_type=None, args=(), **kwargs)

Parameters:

  1. Func: A custom/in-built function that can be applied on the rows/columns.
  2. axis: {columns (1), index (0)}
  3. skipna: Ignore the NA/null values when calculating the result.
  4. result_type: Returned type of the result like Series,DataFrame, etc.
  5. args: Specify the arguments.

Method 1: Apply() with Custom Function

To do some operation on all the rows in the Pandas DataFrame, we need to write a function that will do the computation and pass the function name within the apply() method. By this, the function is applied to each and every row.

pandas.DataFrame_object.apply(custom_function)

Example:
In this example, we are having a DataFrame named “analysis” with 4 columns of integer type. Now, we write two custom functions on these 4 columns.

  1. The “operation1” adds rows in all the columns. The result across each column is stored in the “Addition Result” column.
  2. The “operation2” multiplies the rows in all the columns. The result across each column is stored in the “Multiplication Result” column.
import pandas

# Create the dataframe using lists
analysis = pandas.DataFrame([[23,1000,34,56],
                             [23,700,11,0],
                             [23,20,4,2],
                             [21,400,32,45],
                             [21,100,456,78],
                             [23,800,90,12],
                             [21,400,32,45],
                             [20,120,1,67],
                             [23,100,90,12],
                             [22,450,76,56],
                             [22,40,0,1],
                             [22,12,45,0]
                             ],columns=[‘points1’,‘points2’,‘points3’,‘points4’])

# Display the DataFrame – analysis
print(analysis)

# Function that adds each row for all columns.
def operation1(row):
   return row[0]+row[1]+row[2]+row[3]

   # Function that adds each row for all columns.
def operation2(row):
   return row[0]*row[1]*row[2]*row[3]

# Pass the function to the apply() method and store it in ‘Addition Result’ column
analysis[‘Addition Result’] = analysis.apply(operation1, axis=1)

# Pass the function to the apply() method and store it in ‘Multiplication Result’ column
analysis[‘Multiplication Result’] = analysis.apply(operation2, axis=1)

print()

print(analysis)

Output:

Explanation:
We pass the “operation1” and “operation2” to the apply() function separately one after the other. You can see that the sum of all values across each row is stored in the “Addition Result” column and the product of all values across each row is stored in “Multiplication Result” column.

Method 2: Apply() with Lambda Expression

Here, we pass the lambda as a parameter to the apply() function and do the computation inside itself.

pandas.DataFrame_object.apply(lambda x: computation,axis=1)

Example:
Let’s add and multiply four rows like the previous example and store them in two columns.

import pandas

# Create the dataframe using lists
analysis = pandas.DataFrame([[23,1000,34,56],
                             [23,700,11,0],
                             [23,20,4,2],
                             [21,400,32,45],
                             [21,100,456,78],
                             [23,800,90,12],
                             [21,400,32,45],
                             [20,120,1,67],
                             [23,100,90,12],
                             [22,450,76,56],
                             [22,40,0,1],
                             [22,12,45,0]
                             ],columns=[‘points1’,‘points2’,‘points3’,‘points4’])

# Add all rows and store them in the ‘Addition Result’ column.
analysis[‘Addition Result’] = analysis.apply(lambda record : record[0]+record[1]+record[2]+record[3], axis=1)

# Multiply all rows and store them in the ‘Multiplication Result’ column.
analysis[‘Multiplication Result’] = analysis.apply(lambda record : record[0]*record[1]*record[2]*record[3], axis=1)

print()

print(analysis)

Output:

Explanation:
The expressions that are used are as follows:

# Add all rows and store them in the ‘Addition Result’ column.
analysis[‘Addition Result’] = analysis.apply(lambda record : record[0]+record[1]+record[2]+record[3], axis=1)

# Multiply all rows and store them in the ‘Multiplication Result’ column.
analysis[‘Multiplication Result’] = analysis.apply(lambda record : record[0]*record[1]*record[2]*record[3], axis=1)

You can see that the sum of all values across each row is stored in the “Addition Result” column and the product of all values across each row is stored in the “Multiplication Result” column.

Method 3: Apply() with Pandas.Series

If you want to modify the row separately or you want to update all rows individually, you can do it by passing the Series inside the lambda expression.

pandas.DataFrame_object.apply(lambda x: pandas.Series(computation),axis=1)

Example:
Let’s subtract 10 from all columns.

import pandas

# Create the dataframe using lists
analysis = pandas.DataFrame([[23,1000,34,56],
                             [23,700,11,0],
                             [23,20,4,2],
                             [21,400,32,45],
                             [21,100,456,78],
                             [23,800,90,12],
                             [21,400,32,45],
                             [20,120,1,67],
                             [23,100,90,12],
                             [22,450,76,56],
                             [22,40,0,1],
                             [22,12,45,0]
                             ],columns=[‘points1’,‘points2’,‘points3’,‘points4’])

# Subtract 10 from all the rows
analysis=analysis.apply(lambda record : pandas.Series([record[0]–10,record[1]–10,record[2]–10,record[3]–10]), axis=1)

print(analysis)

Output:

Explanation:
The expressions that are used are as follows:

analysis=analysis.apply(lambda record : pandas.Series([record[0]–10,record[1]–10,record[2]–10,record[3]–10]), axis=1)

You can see that the values in all columns are subtracted from 10.

Method 4: Apply() with NumPy Functions

Let’s use the NumPy functions to perform the computation on all rows in Pandas DataFrame.

pandas.DataFrame_object.apply(numpy function,axis=1)

Example:
Let’s use the NumPy function to return the following:

  1. The sum of all rows using numpy.sum().
  2. The average of all rows using numpy.mean().
  3. The maximum among each row using numpy.max().
  4. The minimum among each row using numpy.min().

We store the result in four different columns.

import pandas
import numpy

# Create the dataframe using lists
analysis = pandas.DataFrame([[23,1000,34,56],
                             [23,700,11,0],
                             [23,20,4,2],
                             [21,400,32,45],
                             [21,100,456,78],
                             [23,800,90,12],
                             [21,400,32,45],
                             [20,120,1,67],
                             [23,100,90,12],
                             [22,450,76,56],
                             [22,40,0,1],
                             [22,12,45,0]
                             ],columns=[‘points1’,‘points2’,‘points3’,‘points4’])

# Get total sum of rows and store in ‘Sum Result’
analysis[‘Sum Result’] = analysis.apply(numpy.sum, axis = 1)

# Get average of rows and store in ‘Sum Result’
analysis[‘Average Result’] = analysis.apply(numpy.mean, axis = 1)

# Get maximum value from each row and store in ‘Max Result’
analysis[‘Max Result’] = analysis.apply(numpy.max, axis = 1)

# Get minimum value from each row and store in ‘Min Result’
analysis[‘Min Result’] = analysis.apply(numpy.min, axis = 1)

print(analysis)

Output:

Conclusion

We provided this guide to explain how to utilize the apply() function to every row. Our main aim is to provide you with a good, easy, and detailed explanation of this “apply()” function concept. We demonstrated four distinct examples in which we showed how to apply the function to every row in “pandas” with the help of the “apply()” function. We explained that when we want to implement any function to every row in DataFrame in Pandas, we utilize the “apply()” function for this purpose.

Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
Previous ArticlePandas Argmax()
Next Article Skrillex, Fred Again.., And Four Tet Are Bringing Their Pop-Up Performances To Madison Square Garden

Related Posts

How to Fix “Not connected – No connections are available” Error in Windows

How to Fix “Blurry Font Problem” in Windows 10

How to Fix “Can’t create new folder” in Windows 10

Add A Comment

Leave A Reply Cancel Reply

Grimes Explained Why She’s ‘Purposefully’ Trying To Make Herself ‘Infinitely Less Accessible’

It Appears That Netflix May Have Edited One Of Chris Rock’s Jokes About Will Smith In His Comedy Special

There’s A Rumor That Cardi B And Megan Thee Stallion Want To Remake A Cult-Classic Halle Berry Movie And Cardi Addressed It

The Biggest Takeaways From ‘Bel-Air’ Season 2, Episode 3

  • Homepage
  • Sitemap
© 2023 Biz Assurance - Designed by Curtiex Ventures.

Type above and press Enter to search. Press Esc to cancel.