索引numpy数组中的日期时间



我有一个numpy数组,大致如下:

data    
array([(datetime.datetime(2009, 1, 6, 2, 30), 17924.0, 0.0),....
           (datetime.datetime(2009, 1, 29, 16, 30), 35249.2, 521.25], 
         dtype=[('timestamp', '|O4'), ('x1', '<f8'), ('x2', '<f8')])

我希望能够根据第一列对数据进行索引(即使用日期时间对象),这样我就可以访问特定年份/月/日的数据,如下所示:

data[data['timestamp'].year == 2009]

这显然不起作用。我唯一能想到的就是添加额外的列(例如"年"列),所以这会起作用:

data[data['year'] == 2009]

这似乎是一种效率相当低的做事方式(会复制大量数据),尤其是如果我想对所有其他时间间隔进行索引。。。有更好的方法吗?

提前谢谢。

使用熊猫。"pandas是一个开源的BSD许可库,为Python编程语言提供高性能、易用的数据结构和数据分析工具。"

文档中有很多例子,但你可以这样做:

import pandas
import numpy as np
import datetime as dt
# example values
dates = np.asarray(pandas.date_range('1/1/2000', periods=8))
# create a dataframe
df = pandas.DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])
# date you want
date=dt.datetime(2000,1,2)
# magic :)
print df.xs(date)

我建议尽快学习这个模块。这绝对是非同寻常的。这是一个非常简单的例子。查看非常详尽的文档。

好的,所以我认为我解决了这个问题(使用pandas,如上面strimp099所建议的),特别是使用"GroupBy"对象(pandas:GroupBy:split-apply-comport)

详细说明上面使用的示例:

import pandas
import numpy as np
import datetime as dt
# example values
dates = np.asarray(pandas.DateRange('1/1/2000', periods=200))
# create a dataframe
df = pandas.DataFrame(np.random.randn(200, 4), index=dates, columns=['A', 'B', 'C', 'D'])
# create a GroupBy object
grouped_data = df.groupby(lambda x: x.month)
#magic
grouped_data.mean()
              A         B         C         D
month                                        
1     -0.492648 -0.038257 -0.224924  0.130182
2     -0.178995  0.236042 -0.471791 -0.369913
3     -0.261866 -0.024680 -0.107211 -0.195742
4      0.215505  0.077079 -0.057511  0.146193
5     -0.097043 -0.335736  0.302811  0.120170
6      0.187583  0.221954 -0.290655 -0.077800
7     -0.134988  0.013719 -0.094334 -0.107402
8     -0.229138  0.056588 -0.156174 -0.067655
9      0.043746  0.077781  0.230035  0.344440
10    -0.533137 -0.683788  0.395286 -0.957894

(即按月份分组的数据平均值)

此外,要进行多个分组(即,在我的情况下为年和月),这可能会有所帮助:

grouped_data = df.groupby(lambda x: (x.year,x.month))

干杯!

您还可以使用numpy中的日期时间dtype。我还没有对这两种方法进行基准测试,但它们可能非常接近。这里有一个例子:

import datetime
import numpy as np

def data_in(dates, year=2009):
    """ Return the dates within the given year. 
    Works only with dates being a numpy array with a datetime dtype.
    """
    from_date = np.array(('{}-01-01'.format(year), ), dtype='M8')
    to_date = np.array(('{}-12-31'.format(year),), dtype='M8')
    return dates[(dates > from_date) & (dates < to_date)]

if __name__ == '__main__':
    data = np.array(
        [
            (datetime.datetime(2009, 1, 6, 2, 30), 17924.0, 0.0),
            (datetime.datetime(2009, 1, 29, 16, 30), 35249.2, 521.25),
            (datetime.datetime(2011, 1, 29, 16, 30), 35249.2, 521.25),
        ], 
        dtype=[('timestamp', 'M8'), ('x1', '<f8'), ('x2', '<f8')]
    )
    for year in [2009, 2010, 2011]:
        print ' Timestamps in {}:n {}'.format( year, data_in(data['timestamp'], year))

最新更新