I want to create a conditional column using for loop but the condition is not working.
Data:
Index Salesman ID OrderDate Final_Price month
0 2887 01-01-2020 57.8259 1
1 3532 04-01-2020 297.5574 1
2 2911 07-01-2020 107.3754 1
3 3276 10-01-2020 151.8066 1
4 3013 13-01-2020 82.0116 1
239 2933 18-12-2021 73.3788 12
240 3093 21-12-2021 453.5685 12
241 3460 24-12-2021 102.606 12
242 3456 27-12-2021 54.978 12
243 3665 30-12-2021 123.7104 12
I want to create a new column named "Quarter" using the following logic. I found other ways to do this but I would like to know what is wrong with this code:
for i in sales_data["month"]:
if i >= 1 and i <= 3:
sales_data["Quarter"] = "Q1"
elif i >= 4 and i <= 6:
sales_data["Quarter"] = "Q2"
elif i >= 7 and i <= 9:
sales_data["Quarter"] = "Q3"
else:
sales_data["Quarter"] = "Q4"
This code returns the following:
Salesman ID OrderDate Final_Price month Quarter
2887 01-01-2020 57.8259 1 Q4
3532 04-01-2020 297.5574 1 Q4
2911 07-01-2020 107.3754 1 Q4
3276 10-01-2020 151.8066 1 Q4
3013 13-01-2020 82.0116 1 Q4
... ... ... ... ...
2933 18-12-2021 73.3788 12 Q4
3093 21-12-2021 453.5685 12 Q4
3460 24-12-2021 102.606 12 Q4
3456 27-12-2021 54.978 12 Q4
3665 30-12-2021 123.7104 12 Q4
The issue with the output is that the column "Quarter" returned "Q4" for all rows.
I found a way to correct this:
Quarter = []
for i in sales_data["month"]:
if i <= 3:
Quarter.append("Q1")
elif i >= 4 and i <= 6:
Quarter.append("Q2")
elif i >= 7 and i <= 9:
Quarter.append("Q3")
else:
Quarter.append("Q4")
sales_data["Quarter"] = Quarter
CodePudding user response:
You can generate the quarter by apply
ing a function to the month:
df['Quarter'] = df['month'].apply(lambda m: f'Q{(m-1)//3 1}')
The function computes the quarter number as
(month - 1) // 3 1
So
1-3 => Q1
4-6 => Q2
7-9 => Q3
10-12 => Q4
CodePudding user response:
Using the math
module, we can also do it quickly.
from math import ceil
for i in sales_data["month"]:
quarter = ceil(i/3)
sales_data["Quarter"] = "Q%d" % quarter
P.S - Above code is not tested. It's just pseudo code so that you can change it accordingly.