
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Apply function to every row in a Pandas DataFrame
By applying a lambda function to each row
Example
import pandas as pd df = pd.DataFrame([(10, 3, 13),(0, 42, 11),(26, 52, 1)], columns=list('xyz')) print("Existing matrix") print(df) NewMatrix = df.apply(lambda a: a + 10, axis=1) print("Modified Matrix") print(NewMatrix)
Output
Running the above code gives us the following result −
Existing matrix x y z 0 10 3 13 1 0 42 11 2 26 5 21 Modified Matrix x y z 0 20 13 23 1 10 52 21 2 36 62 11
By applying a User Defined function
Example
import pandas as pd def SquareData(x): return x * x df = pd.DataFrame([(10, 3, 13), (0, 42, 11), (26, 52, 1)], columns=list('xyz')) print("Existing matrix") print(df) NewMatrix = df.apply(SquareData, axis=1) print("Modified Matrix") print(NewMatrix)
Output
Running the above code gives us the following result −
Existing matrix x y z 0 10 3 13 10 42 1 1 2 26 52 1 Modified Matrix x y z 0 100 9 169 1 0 1764 121 2 676 2704 1
- Related Articles
- Apply function to every row in a Pandas DataFrame in Python
- How to apply the aggregation list on every group of pandas DataFrame?
- Apply uppercase to a column in Pandas dataframe
- Apply uppercase to a column in Pandas dataframe in Python
- How to get nth row in a Pandas DataFrame?
- Add a row at top in pandas DataFrame
- How to add header row to a Pandas Dataframe?
- Python Pandas - How to delete a row from a DataFrame
- How to get the row count of a Pandas DataFrame?
- How to add one row in an existing Pandas DataFrame?
- How to append a list as a row to a Pandas DataFrame in Python?
- Python Pandas – How to use Pandas DataFrame tail( ) function
- Deleting a DataFrame row in Python Pandas based on column value
- Create a Pandas Dataframe by appending one row at a time
- Python - Change column names and row indexes in Pandas DataFrame

Advertisements