2017-10-10 61 views
2

我曾處理過一個數據集,並能夠以這種方式重新排列它(pastebin)。添加小時(00至23)至日期列

  date type value location 
0 2017-10-03 D 3035 INDIA 
0 2017-10-03 D 3035 INDIA 
0 2017-10-03 D 3035 INDIA 
0 2017-10-03 D 3035 INDIA 
0 2017-10-03 D 3035 INDIA 
    ................................ 
    total 24 rows for D type and India 
    ................................ 
1 2017-10-03 F 3035 INDIA 
1 2017-10-03 F 3035 INDIA 
1 2017-10-03 F 3035 INDIA 
1 2017-10-03 F 3035 INDIA 
1 2017-10-03 F 3035 INDIA 
    ................................ 
    total 24 rows for F type and India 
    ................................ 
2 2017-10-03 D 3035 CHINA 
2 2017-10-03 D 3035 CHINA 
2 2017-10-03 D 3035 CHINA 
2 2017-10-03 D 3035 CHINA 
2 2017-10-03 D 3035 CHINA 
    ................................ 
    total 24 rows for D type and China 
    ................................ 

預期輸出:我想在日期列中添加小時(從00:00到23:00)。 date, type, location恰好有24行。所以我只需要通過日期列環,取前24行,追加時間(00:00至23:00),然後做同樣爲下一個24行等等...

0 2017-10-03 00:00 D 3035 INDIA 
0 2017-10-03 01:00 D 3035 INDIA 
0 2017-10-03 02:00 D 3035 INDIA 
0 2017-10-03 03:00 D 3035 INDIA 
0 2017-10-03 04:00 D 3035 INDIA 
    ................................ 
    total 24 rows for D type and India 
    ................................ 
1 2017-10-03 01:00 F 3035 INDIA 
1 2017-10-03 02:00 F 3035 INDIA 
1 2017-10-03 03:00 F 3035 INDIA 
1 2017-10-03 03:00 F 3035 INDIA 
1 2017-10-03 04:00 F 3035 INDIA 
+1

幫自己一個忙:把時區在T下襬,而你在這。我保證會有一些可憐的悶棍(甚至可能是你自己!)會很高興你做到了。 – jpmc26

+1

@ jpmc26:很好的建議!已添加:) –

回答

3

我想你可以通過索引與cumcount使用groupby的計數,然後將其轉換爲hourto_timedelta被添加到date S:

#convert to datetime if necessary 
df['date'] = pd.to_datetime(df['date']) 

df['date'] += pd.to_timedelta(df.groupby(level=0).cumcount(), unit='H') 

print (df.head(30)) 

       date type value location 
0 2017-10-03 00:00:00 D 3035 INDIA 
0 2017-10-03 01:00:00 D 3035 INDIA 
0 2017-10-03 02:00:00 D 3035 INDIA 
0 2017-10-03 03:00:00 D 3035 INDIA 
0 2017-10-03 04:00:00 D 3035 INDIA 
0 2017-10-03 05:00:00 D 3035 INDIA 
0 2017-10-03 06:00:00 D 3035 INDIA 
0 2017-10-03 07:00:00 D 3035 INDIA 
0 2017-10-03 08:00:00 D 3035 INDIA 
0 2017-10-03 09:00:00 D 3035 INDIA 
0 2017-10-03 10:00:00 D 3035 INDIA 
0 2017-10-03 11:00:00 D 3035 INDIA 
0 2017-10-03 12:00:00 D 3035 INDIA 
0 2017-10-03 13:00:00 D 3035 INDIA 
0 2017-10-03 14:00:00 D 3035 INDIA 
0 2017-10-03 15:00:00 D 3035 INDIA 
0 2017-10-03 16:00:00 D 3035 INDIA 
0 2017-10-03 17:00:00 D 3035 INDIA 
0 2017-10-03 18:00:00 D 3035 INDIA 
0 2017-10-03 19:00:00 D 3035 INDIA 
0 2017-10-03 20:00:00 D 3035 INDIA 
0 2017-10-03 21:00:00 D 3035 INDIA 
0 2017-10-03 22:00:00 D 3035 INDIA 
0 2017-10-03 23:00:00 D 3035 INDIA 
1 2017-10-03 00:00:00 F 3035 INDIA 
1 2017-10-03 01:00:00 F 3035 INDIA 
1 2017-10-03 02:00:00 F 3035 INDIA 
1 2017-10-03 03:00:00 F 3035 INDIA 
1 2017-10-03 04:00:00 F 3035 INDIA 
1 2017-10-03 05:00:00 F 3035 INDIA 
+1

仍未接受?它也值得更多的選票 – Dark

相關問題