我的数据框有一个名为“Time”的列,包含一小时的时间范围,例如19:00-20:00、20:00-21:00、21:00-22:00等等。我还有另一列记录了这些时间段内的数值,例如50、40、10。
我想知道一天中的哪个小时数值最高等等。有没有办法将时间范围转换为单一值,比如19:00,然后提取出小时部分?
Df['Time'] = pd.to_datetime(Df['Time']) 我尝试过这个方法,但得到了错误信息“Out of bounds nanosecond timestamp: 1-01-01 19:00:00”
回答:
首先使用 Series.str.split
,然后通过 to_timedelta
将值转换为时间差:
df = pd.DataFrame({'Time':['19:00-20:00', '20:00-21:00', '21:00-22:00']})df[['first', 'second']] = (df['Time'].str.split('-', expand=True) .add(':00') .apply(pd.to_timedelta))print (df) Time first second0 19:00-20:00 19:00:00 20:00:001 20:00-21:00 20:00:00 21:00:002 21:00-22:00 21:00:00 22:00:00print (df.dtypes)Time objectfirst timedelta64[ns]second timedelta64[ns]dtype: object
或者通过 to_datetime
将其转换为日期时间对象:
df[['first', 'second']] = df['Time'].str.split('-', expand=True).apply(pd.to_datetime)print (df) Time first second0 19:00-20:00 2019-08-04 19:00:00 2019-08-04 20:00:001 20:00-21:00 2019-08-04 20:00:00 2019-08-04 21:00:002 21:00-22:00 2019-08-04 21:00:00 2019-08-04 22:00:00print (df.dtypes)Time objectfirst datetime64[ns]second datetime64[ns]dtype: object
这里可以轻松地提取日期时间的各个部分,例如小时、时间等:
df['hour1'] = df['first'].dt.hourdf['time1'] = df['first'].dt.timeprint (df) Time first second hour1 time10 19:00-20:00 2019-08-04 19:00:00 2019-08-04 20:00:00 19 19:00:001 20:00-21:00 2019-08-04 20:00:00 2019-08-04 21:00:00 20 20:00:002 21:00-22:00 2019-08-04 21:00:00 2019-08-04 22:00:00 21 21:00:00print (df.dtypes)Time objectfirst datetime64[ns]second datetime64[ns]hour1 int64time1 objectdtype: object