2017-03-05 181 views
1

我有一個數據幀,看起來像這樣緩慢:日期時間轉換 - 在大熊貓

date,time,metric_x 
2016-02-27,00:00:28.0000000,31 
2016-02-27,00:01:19.0000000,40 
2016-02-27,00:02:55.0000000,39 
2016-02-27,00:03:51.0000000,48 
2016-02-27,00:05:22.0000000,42 
2016-02-27,00:05:59.0000000,35 

我希望生成一個新列

df['time_slot'] = df.apply(lambda row: time_slot_convert(pd.to_datetime(row['time'])), axis =1) 

其中,

def time_slot_convert(time): 
    return time.hour + 1 

此功能找到此記錄的小時,加上1.

這非常慢。我知道數據是以字符串形式讀取的。有沒有一種更有效的方法來加快速度?

回答

1

更快的是去除apply

df['time_slot'] = pd.to_datetime(df['time']).dt.hour + 1 

print (df) 
     date    time metric_x time_slot 
0 2016-02-27 00:00:28.0000000  31   1 
1 2016-02-27 00:01:19.0000000  40   1 
2 2016-02-27 00:02:55.0000000  39   1 
3 2016-02-27 00:03:51.0000000  48   1 
4 2016-02-27 00:05:22.0000000  42   1 
5 2016-02-27 00:05:59.0000000  35   1