我试图计算几个月之间的圆形距离,以了解两个过程之间的解耦。所以我有一个数据框,其中有一些列,我之间不会以循环方式计算差异。这几个月不是日期,只是从1到12的数字。 我们说
month1 month2
6 8
12 3
8 5
1 11
如果我这样做
month2 - month1
我有一些问题:
8 - 6 = 2
和5 - 8 = -3
没问题,但
3 - 12 = -9
和11 - 1 = 10
,分别应为3
和-2
(12月到3月之间的差异,以及1月和11月之间的差异)
所以我尝试用
monthdelta.monthmod(start, end)
但是,开始和结束必须是日期,似乎无法定义日期只是忽略年和日的月份。如果我将month1和month2定义为日 - 月 - 年的日期,那么12月到1月之间的差异将是11而不是我需要的。
所以将数字定义为几个月是可行的吗?或类似的东西,尽管一年使用monthmod
?或者只是通过其他方式来做这些数字?
有什么建议吗?
答案 0 :(得分:2)
这应该有效:
def diff_between_months(month1, month2):
diff = month1 - month2
if diff > 6:
diff = diff - 12
if diff < -6:
diff = diff + 12
return diff
或者在更少的行中相同:
def diff_between_months(month1, month2):
diff = month1 - month2
return diff - 12 if diff > 6 else diff + 12 if diff < -6 else diff
返回:
>>> diff_between_months(1,11)
2
>>> diff_between_months(11,1)
-2
>>> diff_between_months(12,3)
-3
>>> diff_between_months(3,12)
3
>>> diff_between_months(1,7)
-6
>>> diff_between_months(7,1)
6
如果您希望将diff_between_months(1,7)
更改为if diff < -6
,可以修复if diff <= -6
中的减号。
min(abs(month1 - month2), month1 - month2 + 12, month2 - month1 + 12)
应该可以解决问题。
作为一项功能:
def diff_between_months(month1, month2):
return(min(abs(month1 - month2), month1 - month2 + 12, month2 - month1 + 12))
返回
>>> diff_between_months(1,11)
2
>>> diff_between_months(11,1)
2
>>> diff_between_months(6,6)
0
>>> diff_between_months(6,9)
3
>>> diff_between_months(6,12)
6
>>> diff_between_months(5,12)
5
>>> diff_between_months(7,12)
5
>>> diff_between_months(1,12)
1
>>> diff_between_months(12,1)
1
如果出于某种原因,您的月份可能大于12,请添加第[month1, month2] = [month1 % 12, month2 % 12]
行
答案 1 :(得分:2)
您可以使用:
def diff(month1, month2):
m_min = min(month1, month2)
m_max = max(month1, month2)
diff = m_max - m_min
return diff if diff <= 6 else m_min + 12 - m_max
给出了预期的结果:
>>> diff(1, 11)
2
>>> diff(6, 8)
2
>>> diff(8, 5)
3
>>> diff(12, 3)
3