用熊猫和numpy计算月数

时间:2017-10-11 22:16:44

标签: python pandas numpy

我无法正确计算月份。到目前为止我所拥有的是以及输出。 虽然大部分月份计算得当,但有些则没有。我需要弄明白这一点,因为它让我烦恼。 非常感谢任何想法。

import pandas as pd
import numpy as np
df = pd.DataFrame({
    'StartDate' : ['2017-06-19', '2017-10-01', '2017-09-29', '2017-08-01', '2017-08-01'],
    'EndDate'   : ['2018-06-18', '2017-12-31', '2018-09-30', '2018-07-31', '2017-09-30'],
    'ExpectedMonths'    : [13, 3, 13, 12, 2]
})

df['StartDate'] = pd.to_datetime(df['StartDate'], format='%Y-%m-%d')
df['EndDate'] = pd.to_datetime(df['EndDate'], format='%Y-%m-%d')
df['calculatedMonths'] = (df["EndDate"] - df["StartDate"]) / np.timedelta64(1, 'M')
df['ceilMonths'] = df['calculatedMonths'].apply(np.ceil)

到目前为止的输出: 如您所见,第一行应为13,但我在结果中看到12。 6月到5月应该是12,并增加另一个月(6月)应该是13。

        EndDate     ExpectedMonths      StartDate   calculatedMonths    ceilMonths  
0       2018-06-18  13                  2017-06-19  11.959178           12.0
1       2017-12-31  3                   2017-10-01  2.989794            3.0
2       2018-09-30  13                  2017-09-29  12.024888           13.0
3       2018-07-31  12                  2017-08-01  11.959178           12.0
4       2017-09-30  2                   2017-08-01  1.971293            2.0

我需要调整什么才能获得预期的输出和计算的月份匹配?

2 个答案:

答案 0 :(得分:2)

IIUC:

In [117]: df["EndDate"].dt.to_period('M') - df["StartDate"].dt.to_period('M')
Out[117]:
0    12
1     2
2    12
3    11
4     1
dtype: object

答案 1 :(得分:1)

从6月19日到6月18日将会让你不到12个月,这就是天花板为12的原因。

从6月到6月是12个月不是13 ...这是一整年。 对于指数0和3,您的预期月份应为12。

这是一些更正的代码。

import pandas as pd
import numpy as np
df = pd.DataFrame({
    'StartDate' : ['2017-06-19', '2017-10-01', '2017-09-29', '2017-08-01', '2017-08-01'],
    'EndDate'   : ['2018-06-18', '2017-12-31', '2018-09-30', '2018-07-31', '2017-09-30'],
    'ExpectedMonths'    : [12, 3, 12, 12, 2]
})

df['StartDate'] = pd.to_datetime(df['StartDate'], format='%Y-%m-%d')
df['EndDate'] = pd.to_datetime(df['EndDate'], format='%Y-%m-%d')
df['calculatedMonths'] = (df["EndDate"] - df["StartDate"]) / np.timedelta64(1, 'M')
df['roundedMonths'] = round(df['calculatedMonths'])

print(df)