Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.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_Count_Timestamp - Fatal编程技术网

Python 如何计算数据帧中时间戳之间的值

Python 如何计算数据帧中时间戳之间的值,python,pandas,count,timestamp,Python,Pandas,Count,Timestamp,我有一个熊猫数据框,看起来像这样: >>> df Start_Time End_Time 0 2014-10-16 15:05:17 2014-10-16 17:13:14 1 2014-10-16 14:56:37 2014-10-16 15:07:17 2 2014-10-16 14:25:16 2014-10-16 18:06:17 ... 现在,我有了另一个包含多个时间戳的数据帧: >>

我有一个熊猫数据框,看起来像这样:

>>> df
       Start_Time           End_Time
0      2014-10-16 15:05:17  2014-10-16 17:13:14
1      2014-10-16 14:56:37  2014-10-16 15:07:17
2      2014-10-16 14:25:16  2014-10-16 18:06:17
...
现在,我有了另一个包含多个时间戳的数据帧:

>>> times
       Time           
0      2014-10-16 15:17:17
1      2014-10-16 14:53:37
2      2014-10-16 14:26:16
...
我希望在最后收到的是行数,其中开始时间<时间<结束时间:

>>> times
       Time                 Count          
0      2014-10-16 15:17:17  1
1      2014-10-16 15:05:37  2
2      2014-10-16 14:26:16  1
...
当然,我可以通过迭代时间来完成,并使用loc生成sub_dfs:

  ls_len = []    
  for index, row in times.iterrows():
     sub_df = df.loc[(df['Start_Time']<row['Time']) & (df['End_Time']>row['Time'])]
     ls_len.append(len(sub_df))
  times['Count'] = ls_len
ls_len=[]
对于索引,以时间为单位的行。iterrows()
sub_df=df.loc[(df['Start_Time']行['Time'])]
ls_len.append(len(sub_df))
次数['Count']=ls_len
但这非常耗时,而且感觉不是最优的。有没有一种方法可以在不迭代的情况下执行此操作? 提前非常感谢你们

#这比循环更为理想
  #This is more optimal than looping        
  def count_val(x):
     sub_df = df.loc[(df['Start_Time']<x['Time']) & (df['End_Time']>x['Time'])]
     count = len(sub_df)
     return count

  times['count'] = times.apply(count_val, axis=1)
def计数值(x): sub_df=df.loc[(df['Start_Time']x['Time'])] 计数=len(子单元df) 返回计数 次数['count']=次数。应用(计数值,轴=1)
两个
数据帧的大小是多少?不幸的是,第一个数据帧相当大,包含数百万行。也许您可以将原始
df
拆分为几个较小的数据帧以加快搜索速度?我可以尝试,但这将基于很多假设(例如,每行的持续时间[结束时间-开始时间]应该不会长到几天),所以这会有点风险。更优雅一点:
return((df['Start\u Time']