How to Create a Column in Dataframe Using Loop in Python
To create a column in a dataframe using a loop in Python, you can use the iterrows() function.
The following example shows how to create a column in a dataframe using a loop in Python.
Using iterrows() Function
We can use the iterrows() function to iterate over dataframe rows and create a new column.
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]
})
# Declare empty list
discounted_prices = []
# Calculate discounted_price for each row by iterating it
for index, row in Office_Stuff.iterrows():
if row['Status'] == 1:
discounted_price = row['Price'] * 0.9
else:
discounted_price = row['Price']
discounted_prices.append(discounted_price)
# Add column to dataframe
Office_Stuff['Discounted_Price'] = discounted_prices
# Show updated dataframe
print(Office_Stuff)
Output: 👇️
Date Product_Code Product_Name Price Status Discounted_Price
0 01-03-2023 A-101 Laptop 4500 1 4050.0
1 01-03-2023 A-102 Mobile 550 1 495.0
2 01-03-2023 A-103 Printer 250 1 225.0
3 01-03-2023 B-101 Keyboard 50 0 50.0
4 02-03-2023 B-102 Scanner 350 1 315.0
5 02-03-2023 B-104 Mouse 50 1 45.0
In this example, we use the iterrows() function to iterate over each row of the dataframe Office_Stuff and calculate the discounted price based on the status.
The new column Discounted_Price is then added to the dataframe.
Conclusion
We can use the iterrows() function to create a column in a dataframe using a loop in Python.