Categories
Python Answers

How to change one value based on another value in Python Pandas?

Spread the love

Sometimes, we want to change one value based on another value in Python Pandas.

In this article, we’ll look at how to change one value based on another value in Python Pandas.

How to change one value based on another value in Python Pandas?

To change one value based on another value in Python Pandas, we can use loc to get the rows and columns we want to assign the new values to.

For instance, we write

import pandas
df = pandas.read_csv("test.csv")
df.loc[df.ID == 103, 'FirstName'] = "Matt"
df.loc[df.ID == 103, 'LastName'] = "Jones"

to get the rows and columns with ID value set to 103 and column FirstName and LastName and set them to new values.

We get the values with df.loc.

Conclusion

To change one value based on another value in Python Pandas, we can use loc to get the rows and columns we want to assign the new values to.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *