2016-04-04 1 views
1

を使用して時間への変換時間I持って、次のデータフレーム、dfパンダラムダ

no.  site_number  date    time Class Speed_KPH 
0     11 2016-02-27 00:00:13.0000000 Short   43 
1     11 2016-02-27 00:02:15.0000000 Short   45 
2     11 2016-02-27 00:00:28.0000000 Short   31 
3     11 2016-02-27 00:03:28.0000000 Short   31 

が、私はそれが与えられた時間の終わりを与えるように、time列から、time_slotを新しい列を作成したいです。

no.  site_number  date    time Class Speed_KPH  Hour_slot 
    0     11 2016-02-27 00:00:13.0000000 Short   43 1 
    1     11 2016-02-27 00:02:15.0000000 Short   45 3 
    2     11 2016-02-27 00:00:28.0000000 Short   31 1 
    3     11 2016-02-27 00:03:28.0000000 Short   31 4 

私は時間に時間を変換する機能を定義した後、新しい列、time_slotを定義するためにラムダ計算を使用します。

AttributeError: ("'str' object has no attribute 'hour'", u'occurred at index 0') 

答えて

1

あなたが列to_datetimeを変換する最初の必要

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

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

しかし、私はこのエラーを取得しています。

00:00:13.0000000Hours:Minutes:Secondsされている場合、あなたは、dt.minute、ないdt.hourを使用することができます。

df['time_slot'] = pd.to_datetime(df['time']).dt.minute + 1 
print df 
    site_number  date    time Class Speed_KPH time_slot 
no.                  
0    11 2016-02-27 00:00:13.0000000 Short   43   1 
1    11 2016-02-27 00:02:15.0000000 Short   45   3 
2    11 2016-02-27 00:00:28.0000000 Short   31   1 
3    11 2016-02-27 00:03:28.0000000 Short   31   4 


df['time_slot'] = pd.to_datetime(df['time']).dt.hour + 1 
print df 
    site_number  date    time Class Speed_KPH time_slot 
no.                  
0    11 2016-02-27 00:00:13.0000000 Short   43   1 
1    11 2016-02-27 00:02:15.0000000 Short   45   1 
2    11 2016-02-27 00:00:28.0000000 Short   31   1 
3    11 2016-02-27 00:03:28.0000000 Short   31   1 

あなたがapply機能が必要な場合:

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

df['time_slot'] = pd.to_datetime(df['time']).apply(time_slot_convert) 
print df 
    site_number  date    time Class Speed_KPH time_slot 
no.                  
0    11 2016-02-27 00:00:13.0000000 Short   43   1 
1    11 2016-02-27 00:02:15.0000000 Short   45   3 
2    11 2016-02-27 00:00:28.0000000 Short   31   1 
3    11 2016-02-27 00:03:28.0000000 Short   31   4 

またはlambdaを適用します。

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

df['time_slot']=df.apply(lambda row: time_slot_convert(pd.to_datetime(row['time'])),axis=1) 
print df 
    site_number  date    time Class Speed_KPH time_slot 
no.                  
0    11 2016-02-27 00:00:13.0000000 Short   43   1 
1    11 2016-02-27 00:02:15.0000000 Short   45   3 
2    11 2016-02-27 00:00:28.0000000 Short   31   1 
3    11 2016-02-27 00:03:28.0000000 Short   31   4 
0

は、あなたが試みることができる:

import time 
def time_slot_convert(time): 
    time = time.strptime(x, "%H:%M:%S.0000000") 
    return time.tm_hour + 1