1

我有一个包含重复时间戳的文件,每个时间戳最多两个,实际上它们并不重复,只是第二个时间戳需要添加一个毫秒时间戳。例如,我在文件中有这些,

....
2011/1/4    9:14:00
2011/1/4    9:15:00
2011/1/4    9:15:01
2011/1/4    9:15:01
2011/1/4    9:15:02
2011/1/4    9:15:02
2011/1/4    9:15:03
2011/1/4    9:15:03
2011/1/4    9:15:04
....

我想把它们改成

2011/1/4    9:14:00
2011/1/4    9:15:00
2011/1/4    9:15:01
2011/1/4    9:15:01.500
2011/1/4    9:15:02
2011/1/4    9:15:02.500
2011/1/4    9:15:03
2011/1/4    9:15:03.500
2011/1/4    9:15:04
....

执行此类任务的最有效方法是什么?

4

3 回答 3

1

设置

In [69]: df = DataFrame(dict(time = x))

In [70]: df
Out[70]: 
                 time
0 2013-01-01 09:01:00
1 2013-01-01 09:01:00
2 2013-01-01 09:01:01
3 2013-01-01 09:01:01
4 2013-01-01 09:01:02
5 2013-01-01 09:01:02
6 2013-01-01 09:01:03
7 2013-01-01 09:01:03
8 2013-01-01 09:01:04
9 2013-01-01 09:01:04

查找与上一行的时间差为 0 秒的位置

In [71]: mask = (df.time-df.time.shift()) == np.timedelta64(0,'s')

In [72]: mask
Out[72]: 
0    False
1     True
2    False
3     True
4    False
5     True
6    False
7     True
8    False
9     True
Name: time, dtype: bool

将这些位置设置为使用 5 毫秒的偏移量(在您的问题中,您使用了 500 但可以是任何东西)。这需要 numpy >= 1.7。(并不是说这个语法会在 0.13 中改变以允许更直接的df.loc[mask,'time'] += pd.offsets.Milli(5)

In [73]: df.loc[mask,'time'] = df.time[mask].apply(lambda x: x+pd.offsets.Milli(5))

In [74]: df
Out[74]: 
                        time
0        2013-01-01 09:01:00
1 2013-01-01 09:01:00.005000
2        2013-01-01 09:01:01
3 2013-01-01 09:01:01.005000
4        2013-01-01 09:01:02
5 2013-01-01 09:01:02.005000
6        2013-01-01 09:01:03
7 2013-01-01 09:01:03.005000
8        2013-01-01 09:01:04
9 2013-01-01 09:01:04.005000
于 2013-08-10T12:58:34.053 回答
1

所以这个算法应该工作得很好......我只是用 numpy 的 datetime 数据类型玩得很开心。

In [154]: df
Out[154]: 
                  0
0  2011/1/4 9:14:00
1  2011/1/4 9:15:00
2  2011/1/4 9:15:01
3  2011/1/4 9:15:01
4  2011/1/4 9:15:02
5  2011/1/4 9:15:02
6  2011/1/4 9:15:03
7  2011/1/4 9:15:03
8  2011/1/4 9:15:04


In [155]: ((dt.diff() == 0) * .005)
Out[155]: 
0    0.000
1    0.000
2    0.000
3    0.005
4    0.000
5    0.005
6    0.000
7    0.005
8    0.000
Name: 0, dtype: float64

我们的想法是将这两者加在一起。当然,一个是datetime64,另一个是float64。无论出于何种原因,np.timedelta64不对数组进行操作?无论如何,如果您可以解决可行的 dtype 问题。

于 2013-08-10T12:28:49.107 回答
0

假设-正如您在示例中所示,它们是连续的:

lasttimestamp = None
for ts = readtimestamp(infile): # I will leave this to you
   if ts == lasttimestamp:
      ts += inc_by  # and this
   lasttimestamp = ts
   writetimestamp(outfile, ts) # and this to
于 2013-08-10T08:11:19.037 回答