2016-11-25 25 views
2

我有一個ID和日期的數據框。如何創建另一列的部分重複?

id date 
1 2010-03-09 00:00:00 
1 2010-05-28 00:00:00 
1 2010-10-12 00:00:00 
1 2010-12-10 00:00:00 
1 2011-07-11 00:00:00 

我想重塑數據框,以便我在一列中有一個日期,而在另一列中有下一個日期。見下面

id date     date2 
1 2010-03-09 00:00:00 2010-05-28 00:00:00 
1 2010-05-28 00:00:00 2010-10-12 00:00:00 
1 2010-10-12 00:00:00 2010-12-10 00:00:00 
1 2010-12-10 00:00:00 2011-07-11 00:00:00 

我該如何做到這一點?

回答

2
df['date2'] = df.date.shift(-1)  # use shift function to shift index of the date 
             # column and assign it back to df as a new column 

df.dropna()       # the last row will be nan for date2, drop it if you 
             # don't need it 
# id     date    date2 
#0 1 2010-03-09 00:00:00 2010-05-28 00:00:00 
#1 1 2010-05-28 00:00:00 2010-10-12 00:00:00 
#2 1 2010-10-12 00:00:00 2010-12-10 00:00:00 
#3 1 2010-12-10 00:00:00 2011-07-11 00:00:00 
+0

哦,那是優雅 –

2

看起來Psidom有swaggy答案已經......但因爲我已經在這:

df_new = df.iloc[:-1] 
df_new['date2'] = df.date.values[1:] 
+0

嗯,是啊,這就是我做了太多我自己也是。 –

相關問題