The Wayback Machine - https://web.archive.org/web/20240626143613/https://www.geeksforgeeks.org/python-pandas-apply/
Open In App

Python | Pandas.apply()

Last Updated : 03 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Pandas.apply allow the users to pass a function and apply it on every single value of the Pandas series. It comes as a huge improvement for the pandas library as this function helps to segregate data according to the conditions required due to which it is efficiently used in data science and machine learning.

Installation:

Import the Pandas module into the python file using the following commands on the terminal:

pip install pandas

To read the csv file and squeezing it into a pandas series following commands are used:

import pandas as pd
s = pd.read_csv("stock.csv", squeeze=True)

Syntax:

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

Parameters:

func: .apply takes a function and applies it to all values of pandas series. convert_dtype: Convert dtype as per the function’s operation. args=(): Additional arguments to pass to function instead of series. Return Type: Pandas Series after applied function/operation.

Example #1:

The following example passes a function and checks the value of each element in series and returns low, normal or High accordingly.

PYTHON3




import pandas as pd
 
# reading csv
s = pd.read_csv("stock.csv", squeeze = True)
 
# defining function to check price
def fun(num):
 
    if num<200:
        return "Low"
 
    elif num>= 200 and num<400:
        return "Normal"
 
    else:
        return "High"
 
# passing function to apply and storing returned series in new
new = s.apply(fun)
 
# printing first 3 element
print(new.head(3))
 
# printing elements somewhere near the middle of series
print(new[1400], new[1500], new[1600])
 
# printing last 3 elements
print(new.tail(3))


Output:

Example #2:

In the following example, a temporary anonymous function is made in .apply itself using lambda. It adds 5 to each value in series and returns a new series.

PYTHON3




import pandas as pd
s = pd.read_csv("stock.csv", squeeze = True)
 
# adding 5 to each value
new = s.apply(lambda num : num + 5)
 
# printing first 5 elements of old and new series
print(s.head(), '\n', new.head())
 
# printing last 5 elements of old and new series
print('\n\n', s.tail(), '\n', new.tail())


Output:

0    50.12
1 54.10
2 54.65
3 52.38
4 52.95
Name: Stock Price, dtype: float64

0 55.12
1 59.10
2 59.65
3 57.38
4 57.95
Name: Stock Price, dtype: float64

3007 772.88
3008 771.07
3009 773.18
3010 771.61
3011 782.22
Name: Stock Price, dtype: float64

3007 777.88
3008 776.07
3009 778.18
3010 776.61
3011 787.22
Name: Stock Price, dtype: float64

As observed, New values = old values + 5



Previous Article
Next Article

Similar Reads

Python | Pandas Series.apply()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.apply() function invoke the passed function on each element of the given series
3 min read
Apply uppercase to a column in Pandas dataframe
Analyzing a real world data is some what difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important. One might encounter a situation where we need to uppercase each letter in any specific column in given dataframe. Let's see how
2 min read
Difference between map, applymap and apply methods in Pandas
Pandas library is extensively used for data manipulation and analysis. map(), applymap(), and apply() methods are methods of Pandas library in Python. The type of Output totally depends on the type of function used as an argument with the given method. What is Pandas apply() method The apply() method can be applied both to series and Dataframes whe
3 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
Ways to apply LEFT, RIGHT, MID in Pandas
Many times we need to extract specific characters present within a string in Pandas data frame. In order to solve this issue, we have concept of Left, Right, and Mid in pandas. Example 1: Extract Characters From the Left C/C++ Code # importing pandas library import pandas as pd # creating and initializing a list Cars = ['1000-BMW','2000-Audi','3000
3 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
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
Ways to apply an if condition in Pandas DataFrame
Generally on a Pandas DataFrame the if condition can be applied either column-wise, row-wise, or on an individual cell basis. The further document illustrates each of these with examples. First of all we shall create the following DataFrame : C/C++ Code # importing pandas as pd import pandas as pd # create the DataFrame df = pd.DataFrame({ 'Product
3 min read
Return multiple columns using Pandas apply() method
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,
3 min read
Apply Operations To Groups In Pandas
Prerequisites: Pandas Pandas is a Python library for data analysis and data manipulation. Often data analysis requires data to be broken into groups to perform various operations on these groups. The GroupBy function in Pandas employs the split-apply-combine strategy meaning it performs a combination of — splitting an object, applying functions to
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg