首页 > 解决方案 > 是否有查找日期时间之间差异的功能?

问题描述

我有多个数据帧,它们可以具有相同的时间戳(也是 +-1 秒),其中包含毫秒。因此,当它们在新数据框中都在一起时,我想过滤掉它们彼此相差超过 1 秒的行

是否有dftogether['unique'] = np.ediff1d(dftogether['DateTime']与时间戳类似的功能?

我目前的解决方案有效,但我正在寻找一种正确的方法来做到这一点。假设我有 3 个数据框df1df2df3. 对于每个数据框,我这样做:

df1['DateTime'] = df1['DateTime'].apply(lambda 
x: x.strftime('%Y%d%m%H%M%S'))
df1['DateTime']= df1['DateTime'].astype(np.int64)

这把我DateTime变成了int所以我可以这样做:

dftogether= pd.concat(z, sort=True)
dftogether= dftogether.sort_values('DateTime')
dftogether['unique'] = np.ediff1d(dftogether['DateTime'], to_begin=20181211150613411) <1
dftogether= dftogether[dftogether.unique == False]

然后我将int背面转换为datetime

 dftogether['DateTime'] = dftogether['DateTime'].apply(lambda x: pd.to_datetime(str(x), format='%Y%d%m%H%M%S'))

我不知道如何为时间戳创建示例数据,所以我只复制粘贴部分数据框。

df1

737    2018-12-18 12:37:19.717
738    2018-12-18 12:37:21.936
739    2018-12-18 12:37:22.841
740    2018-12-18 12:37:23.144
877    2018-12-18 12:40:53.268
878    2018-12-18 12:40:56.597
879    2018-12-18 12:40:56.899
880    2018-12-18 12:40:57.300
968    2018-12-18 12:43:31.411
969    2018-12-18 12:43:36.150
970    2018-12-18 12:43:36.452

df2

691    2018-12-18 12:35:23.612
692    2018-12-18 12:35:25.627
788    2018-12-18 12:38:33.248
789    2018-12-18 12:38:33.553
790    2018-12-18 12:38:34.759
866    2018-12-18 12:40:29.487
867    2018-12-18 12:40:31.199
868    2018-12-18 12:40:32.206

df3

699    2018-12-18 12:35:42.452
701    2018-12-18 12:35:45.081
727    2018-12-18 12:36:47.466
730    2018-12-18 12:36:51.796
741    2018-12-18 12:37:23.448
881    2018-12-18 12:40:57.603
910    2018-12-18 12:42:02.904
971    2018-12-18 12:43:37.361

我希望dftogether看起来像这样,但使用时间戳而不是整数

   Unique  DateTime
 737    False  20181812123719
 738    False  20181812123721
 739    False  20181812123722
 741    False  20181812123723
 742     True  20181812123723
 740     True  20181812123723
 785    False  20181812123830
 786    False  20181812123831
 787    False  20181812123832
 787     True  20181812123832
 788    False  20181812123833

所以我可以把那些放在哪里Unique == True

 785    False 2018-12-18 12:38:30
 786    False 2018-12-18 12:38:31
 787    False 2018-12-18 12:38:32
 788    False 2018-12-18 12:38:33
 790    False 2018-12-18 12:38:34
 812    False 2018-12-18 12:39:10
 813    False 2018-12-18 12:39:11

别的东西:我在哪里可以对新的 stackoverflow 提出我的意见 问一个问题?IMO 这真的很糟糕,它一直向上滚动,输入/复制粘贴代码现在真的很混乱,所有的例子都让人分心。我花了30多分钟写这个问题

标签: pythonpandas

解决方案


我将您的 df1 和 df2 加入了一个 df,并创建了一个这样的日期列表:

df = pd.concat([df1,df2]).sort_values('DateTime').reset_index(drop=True)

date_list = [datetime.strptime(i, '%Y-%m-%d %H:%M:%S.%f') for i in df.DateTime.tolist()]

然后我用 1 班轮得到所需的输出:

df[[x>1 for x in [0]+[(j-i).total_seconds() for i,j in zip(date_list, date_list[1:])]]]

要了解它是如何工作的,首先检查以下输出:

[x>1 for x in [0]+[(j-i).total_seconds() for i,j in zip(date_list, date_list[1:])]]

希望这可以帮助。干杯。


推荐阅读