pandas的 DataFrame 提供drop_duplicates可以轻松实现您的目标:
In [121]: arr1 = np.array([dt.datetime(2013, 1, 1), dt.datetime(2013, 1, 1), dt.datetime(2013, 1, 2)])
In [122]: arr2 = np.array([1, 2, 3])
In [123]: df = pd.DataFrame({'date': arr1, 'value': arr2})
In [124]: df
Out[124]:
date value
0 2013-01-01 00:00:00 1
1 2013-01-01 00:00:00 2
2 2013-01-02 00:00:00 3
In [125]: df.drop_duplicates('date')
Out[125]:
date value
0 2013-01-01 00:00:00 1
2 2013-01-02 00:00:00 3
编辑
我一开始就误解了你的问题。请尝试以下一项:
似乎排序是您的主要问题之一,我将示例创建为反向日期时间列表:
In [74]: now = dt.datetime.utcnow()
In [75]: datetimes = [now - dt.timedelta(hours=6) * i for i in range(10)]
In [76]: datetimes
Out[76]:
[datetime.datetime(2013, 5, 8, 16, 47, 32, 60500),
datetime.datetime(2013, 5, 8, 10, 47, 32, 60500),
datetime.datetime(2013, 5, 8, 4, 47, 32, 60500),
datetime.datetime(2013, 5, 7, 22, 47, 32, 60500),
datetime.datetime(2013, 5, 7, 16, 47, 32, 60500),
datetime.datetime(2013, 5, 7, 10, 47, 32, 60500),
datetime.datetime(2013, 5, 7, 4, 47, 32, 60500),
datetime.datetime(2013, 5, 6, 22, 47, 32, 60500),
datetime.datetime(2013, 5, 6, 16, 47, 32, 60500),
datetime.datetime(2013, 5, 6, 10, 47, 32, 60500)]
创建一个DataFrame
bydatetimes
并将列名设置为date
:
In [81]: df = pd.DataFrame(datetimes, columns=['date'])
In [82]: df
Out[82]:
date
0 2013-05-08 16:47:32.060500
1 2013-05-08 10:47:32.060500
2 2013-05-08 04:47:32.060500
3 2013-05-07 22:47:32.060500
4 2013-05-07 16:47:32.060500
5 2013-05-07 10:47:32.060500
6 2013-05-07 04:47:32.060500
7 2013-05-06 22:47:32.060500
8 2013-05-06 16:47:32.060500
9 2013-05-06 10:47:32.060500
DataFrame
接下来,按列排序date
:
In [83]: df = df.sort('date')
然后为 追加一个新列index
:
In [85]: df['index'] = df['date'].apply(lambda x:x.day)
In [86]: df
Out[86]:
date index
9 2013-05-06 10:47:32.060500 6
8 2013-05-06 16:47:32.060500 6
7 2013-05-06 22:47:32.060500 6
6 2013-05-07 04:47:32.060500 7
5 2013-05-07 10:47:32.060500 7
4 2013-05-07 16:47:32.060500 7
3 2013-05-07 22:47:32.060500 7
2 2013-05-08 04:47:32.060500 8
1 2013-05-08 10:47:32.060500 8
0 2013-05-08 16:47:32.060500 8
然后按 分组您的数据index
,然后为每个组获取第一个。如果你熟悉 SQL,它就像SELECT FIRST(*) FROM table GROUP BY table.index
:
In [87]: df = df.groupby('index').first()
In [88]: df
Out[88]:
date
index
6 2013-05-06 10:47:32.060500
7 2013-05-07 04:47:32.060500
8 2013-05-08 04:47:32.060500
现在您可以获得唯一索引:
In [91]: df.index.values
Out[91]: array([6, 7, 8])
并获得独特的日期:
In [92]: df['date'].values
Out[92]:
array(['2013-05-06T18:47:32.060500000+0800',
'2013-05-07T12:47:32.060500000+0800',
'2013-05-08T12:47:32.060500000+0800'], dtype='datetime64[ns]')