【问题标题】:Conditional statements on time series data python关于时间序列数据python的条件语句
【发布时间】:2020-05-18 01:15:58
【问题描述】:

我正在尝试对时间序列数据执行条件语句。如果时间在 1) 00:00:00 和 02:00:00 2) 04:00:00 和 06:00:00 之间,有没有办法将“t_value”设置为零

                   t_value
2019-11-24 00:00:00  4.0
2019-11-24 01:00:00  7.8
2019-11-24 02:00:00  95.1
2019-11-24 03:00:00  78.4
2019-11-24 04:00:00  8.0
2019-11-24 05:00:00  17.50
2019-11-24 06:00:00  55.00
2019-11-24 07:00:00  66.00
2019-11-25 00:00:00  21.00
2019-11-25 01:00:00  12.40 

if-else & np.where 是可能的选项,但我不确定如何按小时实施条件。

【问题讨论】:

  • 所以在你的例子中只有 7am 会有一个值?
  • 是的,但这只是一个例子。我会将其编辑为更合适的示例。

标签: python pandas dataframe time-series conditional-statements


【解决方案1】:

使用 between_time 获取指定时间之间的日期时间,然后使用 loc 分配新值:

我将使用@Ben.T 的示例数据:

df = pd.DataFrame({'t_value':range(1,11)}, 
              index=pd.date_range('2020-05-17 00:00:00', periods=10, freq='1H'))

#get the time indices for the different ranges
m1 = df.between_time('00:00:00','02:00:00').index
m2 = df.between_time('04:00:00','06:00:00').index

#assign 0 to the t_value column matches : 
df.loc[m1|m2] = 0

print(df)

            t_value
2020-05-17 00:00:00 0
2020-05-17 01:00:00 0
2020-05-17 02:00:00 0
2020-05-17 03:00:00 4
2020-05-17 04:00:00 0
2020-05-17 05:00:00 0
2020-05-17 06:00:00 0
2020-05-17 07:00:00 8
2020-05-17 08:00:00 9
2020-05-17 09:00:00 10

【讨论】:

  • 如果我想使用时间范围 (00:00:00,03:00:00) 和 t_value>0 来计算将它们分类为正确 (>0) 和不正确的新列怎么办(=0)?
  • 在我的脑后,听起来你可以放入loc,加上m1|m2 部分。您可以编辑您的问题以进行添加,尽管完全提出一个新问题要好得多
  • 发了一个新问题,stackoverflow.com/questions/61869990/…如果你想试试看
【解决方案2】:

您可以使用 time 从您的日期时间索引中获取时间,并根据您的情况创建掩码。然后使用loc| 将您的掩码连接为或。

#sample data
df = pd.DataFrame({'t_value':range(1,11)}, 
              index=pd.date_range('2020-05-17 00:00:00', periods=10, freq='1H'))

# masks
m1 = ((df.index.time>=pd.to_datetime('00:00:00').time()) 
      & (df.index.time<=pd.to_datetime('02:00:00').time()))
m2 = ((df.index.time>=pd.to_datetime('04:00:00').time())
      & (df.index.time<=pd.to_datetime('06:00:00').time()))

#set the value to 0
df.loc[m1|m2, 't_value'] = 0

print (df)
                     t_value
2020-05-17 00:00:00        0
2020-05-17 01:00:00        0
2020-05-17 02:00:00        0
2020-05-17 03:00:00        4
2020-05-17 04:00:00        0
2020-05-17 05:00:00        0
2020-05-17 06:00:00        0
2020-05-17 07:00:00        8
2020-05-17 08:00:00        9
2020-05-17 09:00:00       10

【讨论】:

    猜你喜欢
    • 2020-05-15
    • 2019-07-08
    • 2021-07-21
    • 2020-10-23
    • 1970-01-01
    • 2019-07-13
    • 2018-02-22
    • 2020-09-04
    • 2019-10-15
    相关资源
    最近更新 更多