Python Pandas日期时间索引创建数据框

时间:2018-10-11 18:07:05

标签: python pandas numpy datetime

我有一些时间序列数据,我试图在Pandas中创建单独的数据框,该数据框将基于索引是一周中的特定日期还是特定时间的另一个日期而为0或1。

例如,我可以使用以下内容构成一些数据:

import pandas as pd
import numpy as np
from numpy.random import randint

#time = pd.date_range('6/28/2013', periods=2000, freq='5min')
#df = pd.Series(np.random.randint(100, size=2000), index=time)

rng = pd.date_range('10/9/2018 00:00', periods=5, freq='6H')
df = pd.DataFrame({'Random_Number':randint(1, 10, 5)}, index=rng)
df.head()

如果我正确执行此操作,则可以创建一个名为Tuesday的数据框,如果day = Tuesday,则为1,否则为0

#The day of the week with Monday=0, Sunday=6
df['Tuesday'] = np.where(df.index.dayofweek == 1, 1, 0)

df.head()

如果时间在上午7点至下午5点之间,我正在努力(在excel中我可以使用if语句嵌入)可以创建一个名为occupied的数据帧。任何提示都会有所帮助,在此先感谢!

df['Occupied'] = np.where(df.index.hour > 7 & df.index.hour < 17, 1, 0)

df.head()

此代码错误并输入类型错误,我不确定该怎么做:

TypeError: unsupported operand type(s) for &: 'int' and 'Int64Index'

2 个答案:

答案 0 :(得分:1)

您缺少()

np.where((df.index.hour > 7) & (df.index.hour < 17), 1, 0)
Out[157]: array([0, 0, 1, 0, 0])

答案 1 :(得分:0)

您可以使用pd.DataFrame.eval

df['Occupied'] = df.eval('7 <= index.dt.hour < 17').astype(int)

print(df)

                     Random_Number  Occupied
2018-10-09 00:00:00              8         0
2018-10-09 06:00:00              8         0
2018-10-09 12:00:00              8         1
2018-10-09 18:00:00              3         0
2018-10-10 00:00:00              2         0