
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Replace Values of a DataFrame with Another DataFrame in Pandas
To replace values of a DataFrame with the value of another DataFrame, use the replace() method n Pandas.
At first, let us first create a DataFrame −
dataFrame1 = pd.DataFrame({"Car": ["Audi", "Lamborghini"], "Place": ["US", "UK"], "Units": [200, 500]})
Let us create another DataFrame −
dataFrame2 = pd.DataFrame({"Car": ["BMW", "Lexus"], "Place": ["India", "Australia"], "Units": [800, 1000]})
Next, get a value from DataFrame2 and replace with a value from DataFrame1 −
# get value from 2nd DataFrame i = dataFrame2['Car'][1] # replacing with a value from the 1st DataFrame j = dataFrame1['Car'][0]
Finally, use the replace() method to replace the value of one DataFrame with value of another DataFrame −
dataFrame2 = dataFrame2.replace(i, j)
Example
Following is the code −
import pandas as pd dataFrame1 = pd.DataFrame({"Car": ["Audi", "Lamborghini"],"Place": ["US", "UK"], "Units": [200, 500]}) print("Dataframe 1...") print(dataFrame1) dataFrame2 = pd.DataFrame({"Car": ["BMW", "Lexus"],"Place": ["India", "Australia"], "Units": [800, 1000]}) print("\nDataframe 2...") print(dataFrame2) ## Get a value from DataFrame2 ## and replace with a value ## from DataFrame1 # getting value from 2nd DataFrame i = dataFrame2['Car'][1] # replacing with a value from the 1st DataFrame j = dataFrame1['Car'][0] # replace values of one DataFrame # with the value of another DataFrame dataFrame2 = dataFrame2.replace(i, j) # Display the updated DataFrame print("\nUpdated Dataframe 2...") print(dataFrame2)
Output
This will produce the following output −
Dataframe 1... Car Place Units 0 Audi US 200 1 Lamborghini UK 500 Dataframe 2... Car Place Units 0 BMW India 800 1 Lexus Australia 1000 Updated Dataframe 2... Car Place Units 0 BMW India 800 1 Audi Australia 1000
Advertisements