How to Add Data to Specific Row and Column in Dataframe in Python
To add data to a specific row and column of a dataframe, you can use the loc[] function.
The following example shows how to add data to a specific row and column of a dataframe using the loc[] function.
Using loc[] Function
We can use the loc[] function to add data to a specific row and column in a dataframe.
Suppose we have the following dataframe:
# Import pandas library
import pandas as pd
# Create dataframe
Office_Stuff = pd.DataFrame({
'Date': ['01-03-2023', '01-03-2023', '01-03-2023', '01-03-2023', '02-03-2023', '02-03-2023'],
'Product_Code': ['A-101', 'A-102', 'A-103', 'B-101', 'B-102', 'B-104'],
'Product_Name': ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse'],
'Price': [4500, 550, 250, 50, 350, 50],
'Status': [1, 1, 1, 0, 1, 1]
})
# Adding data to a specific row and column
Office_Stuff.loc[Office_Stuff['Product_Code'] == 'B-101', 'Price'] = 500
# Print updated dataframe
print(Office_Stuff)
Output: 👇️
Date Product_Code Product_Name Price Status
0 01-03-2023 A-101 Laptop 4500 1
1 01-03-2023 A-102 Mobile 550 1
2 01-03-2023 A-103 Printer 250 1
3 01-03-2023 B-101 Keyboard 500 0
4 02-03-2023 B-102 Scanner 350 1
5 02-03-2023 B-104 Mouse 50 1
In this example, we use the loc[] function to add data to the Price column for the row where the Product_Code is ‘B-101’.