【问题标题】:calculate event duration pandas计算事件持续时间 pandas
【发布时间】:2019-07-21 12:12:15
【问题描述】:

我正在尝试按照this SO post 的第一个答案来计算事件持续时间。帖子中的示例是降雨持续时间,人们想知道降雨的总和以及降雨事件的持续时间(以小时为单位)。

我的场景是类似的时间序列,但应用程序是泵,我想知道泵每天运行的总持续时间(以小时为单位)。我的数据是一个泵速指令,只要泵速大于 0.0,泵就会运行。

首先,我正在将我的 CSV 文件读入 Pandas。

#read CSV file
df = pd.read_csv('C:\\Users\\desktop\\data.csv', index_col='Date', parse_dates=True)

# Converting the index as date
df.index = pd.to_datetime(df.index)

df

除非我在尝试将我的 Date 索引转换为日期时间时遇到问题。这将返回一个ValueError: day is out of range for month

有人知道解决这个问题的方法吗?最后,这是我试图从 SO post 1st answer 重新创建的代码,作者正在创建帮助列...

# create helper columns defining contiguous blocks and day
df['block'] = (df['Pump4VFD'].astype(bool).shift() != df['Pump4VFD'].astype(bool)).cumsum()
df['day'] = df.index.dt.normalize()

# group by day to get unique block count and value count
session_map = df[df['value'].astype(bool)].groupby('day')['block'].nunique()
hour_map = df[df['value'].astype(bool)].groupby('day')['value'].count()

# map to original dataframe
df['sessions'] = df['day'].map(session_map)
df['hours'] = df['day'].map(hour_map)

# calculate result
res = df.groupby(['day', 'hours', 'sessions'], as_index=False)['value'].sum()
res['duration'] = res['hours'] / res['sessions']
res['amount'] = res['value'] / res['sessions']

我的数据如下所示:

                    Pump4VFD
Date                                                                    
1/0/00 12:45 AM          0.0
1/0/00 12:50 AM          0.0
1/0/00 12:55 AM          0.0
1/0/00 12:00 AM          0.0
1/0/00 1:05 AM           0.0

【问题讨论】:

  • 你想要的日期格式是什么 初始日期 -> 最终日期样本?

标签: python pandas data-science


【解决方案1】:

您可能希望将 dayfirst=True 添加到 pd.to_datetime

df.index = pd.to_datetime(df.index,dayfirst=True)

这可能是一种解决方法;但如果不起作用,请尝试以下添加:

df.index = pd.to_datetime(df.index,dayfirst=True,infer_datetime_format=True)

如果您需要进一步说明,请尝试此帖子:ValueError: day is out of range for month

【讨论】:

    猜你喜欢
    • 2021-10-14
    • 2021-09-02
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 2019-01-16
    • 1970-01-01
    相关资源
    最近更新 更多