2017-10-21 101 views
0

我有以下的datetime數據框:如何在datetime數據框中獲取多年的月份數?

df = pd.DataFrame({'year': [2015, 2015 ,2016,2014], 'month': [2,11, 3,9], 'day': [4,21, 5,10]}) 

    df = pd.to_datetime(df) 

我想要得到的 'MONTH_NUMBER'。對應於跨越多年連續一個月算我期望的結果將是:

+1

月份數字如何可以是15? –

+0

@FlashThunder不是月份數,月數 – chrisz

回答

0

(df.year - min(df.year))* 12 + df.month

0

使用

In [5078]: df.month + 12*(df.year - df.year.iloc[0]) 
Out[5078]: 
0  2 
1 11 
2 15 
dtype: int64 

In [5079]: df.month.add(df.year.sub(df.year.iloc[0]).mul(12)) 
Out[5079]: 
0  2 
1 11 
2 15 
dtype: int64 
+0

如果我有這個數據幀:'df = pd.DataFrame({'year':[2015,2015,2016,2014], 'month':[2,11,3 ,9], 'day':[4,21,5,10]}) df = pd.to_datetime(df)',我怎樣才能得到這個輸出:6,15,19,1 – user121

相關問題