Apply a function to single or selected columns or rows in Pandas Dataframe
Last Updated :
04 Sep, 2023
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 Dataframe
Here, we will use different methods to apply a function to single rows by using Pandas dataframe. First lets create a data frame.
Python3
# import pandas and numpy library
import pandas as pd
import numpy as np
# List of Tuples
matrix = [(1, 2, 3),
(4, 5, 6),
(7, 8, 9)]
# Create a DataFrame object
df = pd.DataFrame(matrix, columns = list('xyz'),
index = list('abc'))
print(df)
Output:
x y z
a 1 2 3
b 4 5 6
c 7 8 9
Pandas.apply() allow the users to pass a function and apply it on every single value row of the Pandas dataframe. Here, we squared the 'bth' row.
Python3
# Apply function numpy.square() to lambda
# whose row index is 'b'
df = df.apply(lambda x: np.square(x) if x.name == 'b' else x,
axis = 1)
# Output
print(df)
Output :
x y z
a 1 2 3
b 16 25 36
c 7 8 9
Pandas DataFrame.loc attribute accesses a group of rows in the given DataFrame to squared the 'bth' row.
Python3
# import pandas and numpy library
import pandas as pd
import numpy as np
# List of Tuples
matrix = [(1, 2, 3),
(4, 5, 6),
(7, 8, 9)]
# Create a DataFrame object
df = pd.DataFrame(matrix, columns=list('xyz'),
index=list('abc'))
# Apply a function to one row 'b'
# and assign it back to the same row
df.loc['b'] = df.loc['b'].apply(np.square)
print(df)
Output :
x y z
a 1 2 3
b 16 25 36
c 7 8 9
This mathematical function helps the user to calculate the square value of each element in the array. Here, we are passing b row to make a square of it.
Python3
# import pandas and numpy library
import pandas as pd
import numpy as np
# List of Tuples
matrix = [(1, 2, 3),
(4, 5, 6),
(7, 8, 9)]
# Create a DataFrame object
df = pd.DataFrame(matrix, columns=list('xyz'),
index=list('abc'))
# Apply a function to one row 'b' and
# assign it back to the same row
df.loc['b'] = np.square(df.loc['b'])
# Output
print(df)
Output :
x y z
a 1 2 3
b 16 25 36
c 7 8 9
Apply a function to single column in Pandas Dataframe
Here, we will use different methods to apply a function to single columns by using Pandas Dataframe.
Pandas.apply() allow the users to pass a function and apply it on every single value column of the Pandas Dataframe. Here, we squared the 'zth' column.
Python3
# import pandas and numpy library
import pandas as pd
import numpy as np
# List of Tuples
matrix = [(1, 2, 3),
(4, 5, 6),
(7, 8, 9)]
# Create a DataFrame object
df = pd.DataFrame(matrix, columns=list('xyz'),
index=list('abc'))
# Apply function numpy.square() to lambda
# to find the squares of the values of
# column whose column name is 'z'
new_df = df.apply(lambda x: np.square(x) if x.name == 'z' else x)
# Output
print(new_df)
Output :
x y z
a 1 2 9
b 4 5 36
c 7 8 81
Pandas DataFrame.loc attribute access a group of columns in the given DataFrame to square the 'zth' column.
Python3
# import pandas and numpy library
import pandas as pd
import numpy as np
# List of Tuples
matrix = [(1, 2, 3),
(4, 5, 6),
(7, 8, 9)]
# Create a DataFrame object
df = pd.DataFrame(matrix, columns=list('xyz'),
index=list('abc'))
# Apply a function to one column 'z'
# and assign it back to the same column
df['z'] = df['z'].apply(np.square)
# Output
print(df)
Output :
x y z
a 1 2 9
b 4 5 36
c 7 8 81
This mathematical function helps the user to calculate the square value of each element in the array. Here, we are passing z column to make a square of it.
Python3
# import pandas and numpy library
import pandas as pd
import numpy as np
# List of Tuples
matrix = [(1, 2, 3),
(4, 5, 6),
(7, 8, 9)]
# Create a DataFrame object
df = pd.DataFrame(matrix, columns=list('xyz'),
index=list('abc'))
# Apply a function to one column 'z' and
# assign it back to the same column
df['z'] = np.square(df['z'])
# Output
print(df)
Output:
x y z
a 1 2 9
b 4 5 36
c 7 8 81
Apply function to column and row in the Dataframe
Here. we will see how to apply a function to more than one row and column using df.apply() method.
For ColumnÂ
Here, we applied the function to the x, and y columns.
Python3
# import pandas and numpy library
import pandas as pd
import numpy as np
# List of Tuples
matrix = [(1, 2, 3),
(4, 5, 6),
(7, 8, 9)]
# Create a DataFrame object
df = pd.DataFrame(matrix, columns=list('xyz'),
index=list('abc'))
# Apply function numpy.square()
# for square the values of
# two columns 'x' and 'y'
new_df = df.apply(lambda x: np.square(x) if x.name in ['x', 'y'] else x)
# Output
print(new_df)
Output:
x y z
a 1 4 3
b 16 25 6
c 49 64 9
For Row
Here, we applied the function to the b, and c rows.
Python3
# import pandas and numpy library
import pandas as pd
import numpy as np
# List of Tuples
matrix = [(1, 2, 3),
(4, 5, 6),
(7, 8, 9)]
# Create a DataFrame object
df = pd.DataFrame(matrix, columns=list('xyz'),
index=list('abc'))
# Apply function numpy.square() to
# square the values of two rows
# 'b' and 'c'
new_df = df.apply(lambda x: np.square(x) if x.name in ['b', 'c'] else x,
axis=1)
# Output
print(new_df)
Output:
x y z
a 1 2 3
b 16 25 36
c 49 64 81
Similar Reads
Apply a function to each row or column in Dataframe using pandas.apply()
Let's explore how to use the apply() function to perform operations on Pandas DataFrame rows and columns.pandas.DataFrame.apply() method is used to apply a function along the axis of a DataFrame (either rows or columns). Syntax: DataFrame.apply(func, axis=0, raw=False, result_type=None, args=None, *
5 min read
How to Select Single Column of a Pandas Dataframe
In Pandas, a DataFrame is like a table with rows and columns. Sometimes, we need to extract a single column to analyze or modify specific data. This helps in tasks like filtering, calculations or visualizations. When we select a column, it becomes a Pandas Series, a one-dimensional data structure th
2 min read
How to Select Rows & Columns by Name or Index in Pandas Dataframe - Using loc and iloc
When working with labeled data or referencing specific positions in a DataFrame, selecting specific rows and columns from Pandas DataFrame is important. In this article, weâll focus on pandas functionsâloc and ilocâthat allow you to select rows and columns either by their labels (names) or their int
4 min read
Find duplicate rows in a Dataframe based on all or selected columns
Duplicating rows in a DataFrame involves creating identical copies of existing rows within a tabular data structure, such as a pandas DataFrame, based on specified conditions or across all columns. This process allows for the replication of data to meet specific analytical or processing requirements
5 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 P
7 min read
Pandas filter a dataframe by the sum of rows or columns
In this article, we will see how to filter a Pandas DataFrame by the sum of rows or columns. This can be useful in some conditions. Let's suppose you have a data frame consisting of customers and their purchased fruits. Â The rows consist of different customers and columns contain different types of
4 min read
PySpark DataFrame - Select all except one or a set of columns
In this article, we are going to extract all columns except a set of columns or one column from Pyspark dataframe. For this, we will use the select(), drop() functions. But first, let's create Dataframe for demonestration. Python3 # importing module import pyspark # importing sparksession from pyspa
2 min read
Select any row from a Dataframe using iloc[] and iat[] in Pandas
In this article, we will learn how to get the rows from a dataframe as a list, using the functions ilic[] and iat[]. There are multiple ways to do get the rows as a list from given dataframe. Letâs see them will the help of examples. Python import pandas as pd # Create the dataframe df = pd.DataFram
2 min read
Sort Rows or Columns in Pandas Dataframe Based on Values
Sorting is a fundamental operation when working with data in Pandas. Whether you need to arrange rows in ascending or descending order or reorder columns based on values, Pandas provides powerful functions to make sorting easy and efficient. In this article, we'll explore different ways to sort rows
4 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
2 min read