2017-10-11 96 views
0

我很難正確計算月份。到目前爲止,我所得到的結果都低於輸出結果。 雖然大部分月份計算正確,但有些則沒有。我需要弄明白這一點,因爲它在擾亂我。 任何想法,不勝感激。使用熊貓和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。六月到五月是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

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

從6月19日去到6月18日是會得到你剛剛12個月這也是爲什麼天花板是12

從六月到六月是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)