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
Apply function to every row in a Pandas DataFrame Applying a function to every row in a Pandas DataFrame means executing custom logic on each row individually. For example, if a DataFrame contains columns 'A', 'B' and 'C', and you want to compute their sum for each row, you can apply a function across all rows to generate a new column. Letâs explor
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
2 min read