UPDATE:谢谢@piRSquared https://stackoverflow.com/questions/39400684/pandas-keeping-only-first-row-of-data-in-each-60-second-bin/39400864?noredirect=1#comment66127957_39400864- 他注意到我之前的解决方案是不正确的。这是另一种尝试:
data:
In [8]: df = pd.DataFrame(dict(time=pd.date_range('2001-01-01', periods=20, freq='9S'), value=np.random.rand(20)))
In [9]: df
Out[9]:
time value
0 2001-01-01 00:00:00 0.440696
1 2001-01-01 00:00:09 0.135540
2 2001-01-01 00:00:18 0.008243
3 2001-01-01 00:00:27 0.389259
4 2001-01-01 00:00:36 0.128253
5 2001-01-01 00:00:45 0.566704
6 2001-01-01 00:00:54 0.386797
7 2001-01-01 00:01:03 0.426411
8 2001-01-01 00:01:12 0.438114
9 2001-01-01 00:01:21 0.918711
10 2001-01-01 00:01:30 0.715565
11 2001-01-01 00:01:39 0.422044
12 2001-01-01 00:01:48 0.199396
13 2001-01-01 00:01:57 0.827872
14 2001-01-01 00:02:06 0.986887
15 2001-01-01 00:02:15 0.305749
16 2001-01-01 00:02:24 0.030092
17 2001-01-01 00:02:33 0.338214
18 2001-01-01 00:02:42 0.773635
19 2001-01-01 00:02:51 0.816478
解决方案:
In [10]: df.groupby((df.time - df.loc[0, 'time']).dt.total_seconds() // 60, as_index=False).first()
Out[10]:
time value
0 2001-01-01 00:00:00 0.440696
1 2001-01-01 00:01:03 0.426411
2 2001-01-01 00:02:06 0.986887
解释:
In [17]: (df.time - df.loc[0, 'time']).dt.total_seconds()
Out[17]:
0 0.0
1 9.0
2 18.0
3 27.0
4 36.0
5 45.0
6 54.0
7 63.0
8 72.0
9 81.0
10 90.0
11 99.0
12 108.0
13 117.0
14 126.0
15 135.0
16 144.0
17 153.0
18 162.0
19 171.0
Name: time, dtype: float64
In [18]: (df.time - df.loc[0, 'time']).dt.total_seconds() // 60
Out[18]:
0 -0.0
1 0.0
2 0.0
3 0.0
4 0.0
5 0.0
6 0.0
7 1.0
8 1.0
9 1.0
10 1.0
11 1.0
12 1.0
13 1.0
14 2.0
15 2.0
16 2.0
17 2.0
18 2.0
19 2.0
Name: time, dtype: float64
旧的错误答案:
In [102]: df[df.time.diff().fillna(pd.Timedelta('60S')) >= pd.Timedelta('60S')]
Out[102]:
time value
0 2016-05-11 13:00:10.841015028 0.215978
1 2016-05-11 13:02:05.760595780 0.155666
9 2016-05-11 13:04:24.660609068 0.211649
解释: