Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫-确定事件的持续时间_Python_Pandas - Fatal编程技术网

Python 熊猫-确定事件的持续时间

Python 熊猫-确定事件的持续时间,python,pandas,Python,Pandas,我有一个Panadas数据帧,其中包含各种操作(OpID)的测量值(Val),以及测量发生的时间戳(OpTime) 我希望生成只显示测量返回零的时间段的输出。Start列将显示一系列优化中的第一个,这些优化导致零,End将包含第一个Val的非零优化 鉴于上述样本数据,我期望的结果是: OpID Start End 143 2014-01-01 02:40:03 2014-01-01 02:5

我有一个Panadas数据帧,其中包含各种操作(OpID)的测量值(Val),以及测量发生的时间戳(OpTime)

我希望生成只显示测量返回零的时间段的输出。Start列将显示一系列优化中的第一个,这些优化导致零,End将包含第一个Val的非零优化

鉴于上述样本数据,我期望的结果是:

OpID                      Start                     End
 143        2014-01-01 02:40:03     2014-01-01 02:50:01
 143        2014-01-01 02:55:01     2014-01-01 03:00:01
 212        2014-01-01 02:17:02     2014-01-01 02:30:01

如何使用
pivot()


要获得您介绍的内容,可能只需:

pf3 = pd.DataFrame(pf2.pivot(index='idx2', columns='State', values='OpTime'))
pf3.index=asarray(pf3.index.values, 'int')

如果组中的最后一个度量值为零会怎么样?理想情况下,结果将包括一行,该行的结尾列中有null、NaN或OpTime。我认为这个案例是“额外的信贷”,因为我目前的需要,正确的答案不需要处理这种情况。这个解决方案取决于“代码>结束<代码/代码>和<代码>开始/代码>在您的时间序列中成对出现的假设。DSM所描述的情况肯定会打破这一假设。除此之外,您可能还需要考虑如何处理第一个时间点为零的情况。我不知道您是否希望将其视为
开始
,因为在开始测量之前,系统可能(可能)已经处于
val==0
状态。不管怎样,只是一些想法。这完全取决于你的应用程序和现实世界的问题。效果很好!谢谢你的帮助。当我输入更多数据时,我可能需要处理第一个和最后一个测量值为零的边缘情况,但这正是我现在需要的。我确实对“唯一值”乘数进行了编辑,因为0.1正在滚动,这导致了问题,所以我使用了0.00000001。
import numpy as np
import pandas as pd

df['Zeros'] = (df['Val']==0)
df['Valdf'] = np.hstack((nan, diff(df['Zeros'].values))) #how do you treat the first cell?
df['Valdr'] = np.hstack((diff(df['Zeros'].values), nan)) #how do you treat the last cell?
pf2 = pd.concat([df[((df['Zeros']!=True)&(df['Valdf']==1))],df[((df['Zeros'])&(df['Valdr']==1))]]).sort_index()
pf2['State'] = np.where(pf2['Zeros'], 'Start', 'End')
pf2['idx2'] = pf2['OpID'] + np.arange(len(pf2))/2*0.00000001 #need unique index for .pivot()
print pf2.pivot(index='idx2', columns='State', values='OpTime')
State                  End                Start
idx2                                           
143.0  2014-01-01 02:50:01  2014-01-01 02:45:01
143.1  2014-01-01 03:00:01  2014-01-01 02:55:01
212.2  2014-01-01 02:30:01  2014-01-01 02:25:01
pf3 = pd.DataFrame(pf2.pivot(index='idx2', columns='State', values='OpTime'))
pf3.index=asarray(pf3.index.values, 'int')