Python Pandas日期时间索引创建数据框 [英] Python Pandas date time index create dataframe

查看:223
本文介绍了Python Pandas日期时间索引创建数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some time series data where I am attempting to create separate dataframes in Pandas that will be a 0 or 1 based on if the index is a particular day of the week and another for a particular time.

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

For example I can make up some data with:

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

And if I am doing this correctly I can create a dataframe named Tuesday that will be a 1 if the day = Tuesday else a 0

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

df.head()

如果时间在7AM& 2之间,我正在努力(在excel中,如果不是else语句,我可以使用嵌入式方法)正在创建名为occupied的数据帧.下午5点.任何提示都会有所帮助,在此先感谢!

What I am struggling with (In excel I can do with embedded if else statements) is creating a dataframe called occupied if the time is in between 7AM & 5PM. Any tips help, thanks in advance!

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

df.head()

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

This code errors out with a type error that I am not sure what to do about:

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

推荐答案

您可以使用

You can use 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

这篇关于Python Pandas日期时间索引创建数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆