How to modify a subset of rows in a pandas DataFrame?

Given a Pandas DataFrame, we have to modify a subset of rows.
Submitted by Pranit Sharma, on June 13, 2022

Sometimes, we need to modify a column value based upon another column value. For example, if you have two columns 'A' and 'B', and you want the value of 'B' to be Nan whenever the value of 'A' becomes 0. This can be done with the help of the pandas.DataFrame.loc property .

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {

# Creating a DataFrame
df = pd.DataFrame(d)

# Display DataFrame
print("Created DataFrame:\n",df,"\n")


Example 1: Modify a subset of rows

Now, we will use the loc property for modifying a column value, suppose we want a value to be set for a column whenever a certain condition is met for another column, we can use the following concept:

df.loc[selection criteria, columns I want] = value

Let us observe the following code snippet,

Python code to modify a subset of rows

# Applying condition and modifying 
# the column value
df.loc[df.A==0, 'B'] = np.nan

# Display modified DataFrame
print("Modified DataFrame:\n",df)


Example 2: Modify a subset of rows

Python Pandas Programs »


Comments and Discussions!


Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.