【问题标题】:Index datetime in numpy arraynumpy数组中的索引日期时间
【发布时间】:2023-04-10 05:40:01
【问题描述】:

我有一个大致像这样的 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]

似乎是一种相当低效的做事方式(并且会复制大量数据) - 特别是如果我还想对所有其他时间间隔进行索引...有没有更好的方法来做到这一点?

提前致谢。

【问题讨论】:

    标签: python datetime numpy recarray


    【解决方案1】:

    使用pandas。 “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)
    

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

    【讨论】:

    • 谢谢!非常感谢 - 这看起来非常有用。 . .也许我可以停止使用 R
    • 对不起,我不确定这是否对我原来的问题有很大帮助。我不想能够选择一个特定的时间戳——我已经可以在 numpy 数组中做到这一点。我真正需要做的是选择一个特定的时间段,并访问该时间段的所有数据(不是单个索引)。例如。从一年中的月份或类似月份中选择数据。如果不创建冗余的数据列,这可能是不可能的。
    【解决方案2】:

    好的,我想我解决了这个问题(使用 pandas,如上面 strimp099 所建议的那样),特别是使用“GroupBy”对象(pandas: Group By: split-apply-combine)

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

    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))
    

    干杯!

    【讨论】:

    • 干得好。我只是想提供一个简单的例子来激发你的胃口。我敢肯定,如果您深入研究文档,您将能够使用内置函数解决您的问题。
    【解决方案3】:

    您还可以在 numpy.xml 中使用 datetime 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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      • 2018-02-09
      • 2011-02-18
      相关资源
      最近更新 更多