【问题标题】:Python Pandas date time index create dataframePython Pandas 日期时间索引创建数据框
【发布时间】:2019-03-16 21:54:02
【问题描述】:

我有一些时间序列数据,我试图在 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 的数据框,如果当天 = 星期二,则为 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 else 语句)创建一个名为 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'

【问题讨论】:

    标签: python pandas numpy datetime


    【解决方案1】:

    你错过了()

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

    【讨论】:

      【解决方案2】:

      你可以使用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
      

      【讨论】:

        猜你喜欢
        • 2017-08-13
        • 1970-01-01
        • 2018-07-31
        • 1970-01-01
        • 1970-01-01
        • 2020-10-09
        • 2021-08-14
        • 1970-01-01
        • 2015-11-23
        相关资源
        最近更新 更多