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

Python | Pandas.apply()

Last Updated : 21 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

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

PYTHON
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


Python | Pandas.apply() – FAQs

What are () Called in Python?

In Python, parentheses () are called several things based on their context:

  1. Tuple: When used to enclose a series of comma-separated values, they define a tuple, a type of immutable sequence in Python.
  2. Function Call: When used after a function name, they execute a function call.
  3. Order of Operations: Parentheses are used to group expressions and override the natural precedence of operators to control the flow and outcome of operations.

What is () Data Type in Python?

When () is used with values separated by commas, it defines a tuple, which is an immutable and ordered sequence type in Python. An empty tuple can be defined by (), while a tuple with one item must use a trailing comma, like (item,).

Example:

# Empty tuple
empty_tuple = ()
# Tuple with one element
single_tuple = (1,)
# Tuple with multiple elements
multi_tuple = (1, 2, 3)

What is the Function of items() in Python?

The items() method is used with dictionaries in Python. It returns a view object that displays a list of a dictionary’s key-value tuple pairs. This method is particularly useful when you need to iterate over the keys and values of a dictionary simultaneously.

Example:

my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in my_dict.items():
print(f"{key}: {value}")
# Output:
# a: 1
# b: 2
# c: 3

What are () Called in Programming?

In the broader context of programming, not just Python:

  1. Parentheses: Generally called parentheses, they are used in many programming languages to initiate function calls, define order in operations, specify tuples, and in expressions to group operators and operands.
  2. Arguments: In the context of functions, anything inside parentheses is typically an argument passed to the function.

What is the Function of items() in Python? (Repeated Question)

The items() method, as previously described, allows access to items in a dictionary, providing a way to iterate over key-value pairs, which can be critical for looping through dictionaries and accessing both keys and values efficiently. Here’s another practical usage in a different context:

Example:

# Counting the frequency of items
counts = {'apple': 1, 'banana': 2}
for fruit, count in counts.items():
print(f"There are {count} {fruit}(s).")
# Output:
# There are 1 apple(s).
# There are 2 banana(s).

This method is especially useful in data handling where dictionaries play a central role in storing and managing data.



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
How to apply functions in a Group in a Pandas DataFrame?
In this article, let's see how to apply functions in a group in a Pandas Dataframe. Steps to be followed for performing this task are - Import the necessary libraries.Set up the data as a Pandas DataFrame.Use apply function to find different statistical measures like Rolling Mean, Average, Sum, Maximum, and Minimum. You can use the lambda function
1 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
How to Use Pandas apply() inplace?
In this article, we are going to see how to use Pandas apply() inplace in Python. In Python, this function is equivalent to the map() function. It takes a function as an input and applies it to a DataFrame as a whole. If you're dealing with data in the form of tables, you'll need to choose which axis your function should act on ( 0 for columns; and
3 min read
Apply function to every row in a Pandas DataFrame
Python is a great language for performing data analysis tasks. It provides a huge amount of Classes and functions which help in analyzing and manipulating data more easily. In this article, we will see how we can apply a function to every row in a Pandas Dataframe. Apply Function to Every Row in a Pandas DataFrameThere are various ways to Perform e
7 min read
How to apply if condition in Pandas DataFrame
In Pandas DataFrames, applying conditional logic to filter or modify data is a common task. Let's explore different ways to apply an 'if condition' in Pandas DataFrame. Using apply() with a Lambda FunctionWe can apply an "if condition" by using apply() with a lambda function. This allows you to apply a custom function row-wise or column-wise to you
4 min read
Python | pandas.to_markdown() in Pandas
With the help of pandas.to_markdown() method, we can get the markdown table from the given dataframes by using pandas.to_markdown() method. Syntax : pandas.to_markdown() Return : Return the markdown table. Example #1 : In this example we can see that by using pandas.to_markdown() method, we are able to get the markdown table from the given datafram
1 min read
Python Pandas - pandas.api.types.is_file_like() Function
In this article, we will be looking toward the functionality of pandas.api.types.is_file_like() from the pandas.api.types module with its various examples in the Python language. An object must be an iterator AND have a read or write method as an attribute to be called file-like. It is important to note that file-like objects must be iterable, but
2 min read
Apply function to each element of a list - Python
In this article, we will learn how to apply a function to each element of a Python list. Let's see what exactly is Applying a function to each element of a list means: Suppose we have a list of integers and a function that doubles each integer in this list. On applying the function to the list, the function should double all the integers in the lis
2 min read
How to apply different titles for each different subplots using Plotly in Python?
Prerequisites: Python Plotly In this article, we will explore how to apply different titles for each different subplot. One of the most deceptively-powerful features of data visualization is the ability for a viewer to quickly analyze a sufficient amount of information about data when pointing the cursor over the point label appears. It provides us
2 min read
Apply a Gauss filter to an image with Python
A Gaussian Filter is a low pass filter used for reducing noise (high frequency components) and blurring regions of an image. The filter is implemented as an Odd sized Symmetric Kernel (DIP version of a Matrix) which is passed through each pixel of the Region of Interest to get the desired effect. The kernel is not hard towards drastic color changed
4 min read
Pandas DataFrame hist() Method | Create Histogram in Pandas
A histogram is a graphical representation of the numerical data. Sometimes you'll want to share data insights with someone, and using graphical representations has become the industry standard. Pandas.DataFrame.hist() function plots the histogram of a given Data frame. It is useful in understanding the distribution of numeric variables. This functi
4 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
Pandas Series dt.day_name() Method | Get Day From Date in Pandas
Pandas dt.day_name() method returns the day names of the DateTime Series objects with specified locale. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31 08:45', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime(sr) resu
2 min read
Pandas Series dt.weekday | Find Day of the Week in Pandas
The dt.weekday attribute returns the day of the week. It is assumed the week starts on Monday, which is denoted by 0, and ends on Sunday which is denoted by 6. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day
2 min read
Pandas Series dt.weekofyear Method | Get Week of Year in Pandas Series
The dt.weekofyear attribute returns a Series containing the week ordinal of the year in the underlying data of the given series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index =
2 min read
Pandas Series dt.dayofyear | Get Day of Year in Pandas
Pandas dt.dayofyear attribute returns the ordinal day of the year in the underlying DateTime data in the given Series object. Example: C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr =
2 min read
Pandas Series dt.minute | Extract Minute from DateTime Series in Pandas
Pandas Series.dt.minute attribute returns a NumPy array containing the minutes of the DateTime in the underlying data of the given series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
2 min read
Pandas Series dt.days_in_month | Get Total Number of Days in Month in Pandas
The Pandas dt.days_in_month attribute returns the total number of days in the month for the given Series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime(sr) r
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg