user15929966
user15929966

Reputation:

How to get quarter of year if we have month number?

I am wondering if there is a more elegant way of finding the quarter number from the month number using floordiv or modulo or something else.

import numpy as np
m = np.arange(1,13) # 1,2,...,12
q = []
for i in m:
    if i <= 3: q.append(1)
    elif i <=6: q.append(2)
    elif i<=9: q.append(3)
    else: q.append(4)
    
q # [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
# note: there are four quarters in one year.
# month 123 are quarter 1 and so on.

Are there any elegant methods in python or numpy to do the same operation?

Upvotes: 0

Views: 1341

Answers (4)

Gregg Burns
Gregg Burns

Reputation: 333

Just use a math formula in q to get quarter. Every language has integer division. The + 2 is offset to ensure 1 is lowest returned value. Otherwise answers would be returned (0, 1, 2, 3)

Change m to desired month. You will always get correct quarter

m = 2
q = (m + 2) \ 3

Upvotes: 0

Cfomodz
Cfomodz

Reputation: 516

I like to set up classes for this sort of thing. I don't know if everyone will agree with me that it's more elegant in that if you are just writing a quick and dirty script you can do it in fewer lines with a simple if elif else block, but I would suggest the following is more 'Pythonic'.

import numpy as np
import math
class Month():
    def __init__(self, number=None):
        self.number = number

    def get_quarter(self):
        return ceil(self.number/3)

m = np.arange(1,13)
months = []
for i in m:
    months.append(Month(number=i))
q = []
for month in months:
    q.append(month.get_quarter())

Now... The answer you were probably looking for:

import numpy as np
import math
m = np.arrange(1,13)
q = []
for i in m:
    q.append(ceil(i/3))

Upvotes: 1

Random Davis
Random Davis

Reputation: 6857

You can use math.ceil on the result of dividing the month number by 3:

from math import ceil
q = [ceil(a / 3) for a in range(1, 13)]
print(q)

Output:

[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

The more general formula is:

ceil(month_num / (12 / num_segments))

Alternatively:

ceil(month_num * num_segments / 12)

Where num_segments is the number of segments you are dividing the year up into.

Upvotes: 5

BhishanPoudel
BhishanPoudel

Reputation: 17164

You could also do this:

import numpy as np
m = np.arange(1,13)
q = np.ceil(m/3).astype(int)
print(q)

# [1 1 1 2 2 2 3 3 3 4 4 4]

Upvotes: 2

Related Questions