【问题标题】:Extract items from array: between given values/conditions从数组中提取项目:在给定值/条件之间
【发布时间】:2012-01-09 15:19:22
【问题描述】:

我在数组中有许多时间序列数据,并希望以尽可能避免循环的最简单方式提取给定日期之间的值。 这是一个例子:

from numpy import *
from datetime import *

# datetime array
date_a=array([
datetime(2000,1,1),
datetime(2000,1,2),
datetime(2000,1,3),
datetime(2000,1,4),
datetime(2000,1,5),
])

# item array, indices corresponding to datetime array
item_a=array([1,2,3,4,5])

# extract items in a certain date range
# after a certain date, works fine
item_b=item_a[date_a >= (datetime(2000,1,3))] #Out: array([3, 4, 5])

# between dates ?
item_c=item_a[date_a >= (datetime(2000,1,3)) and date_a <= (datetime(2000,1,4))]
# returns: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

这个问题有单线解决方案吗?我查看了 numpy any()all() 以及 where(),但无法找到解决方案。我感谢任何帮助和指示!

【问题讨论】:

    标签: python indexing numpy slice


    【解决方案1】:

    我不清楚你为什么使用item_a 变量。但是要隔离您想要的条目,您只需执行以下操作:

    >>> np.where(np.logical_and(date_a >= datetime(2000,1,3), date_a <= datetime(2000,1,4)))
    (array([2, 3]),)
    

    生成的索引是从零开始的,因此它们对应于数组的第三个和第四个元素。

    编辑: np 应归功于 import numpy as np。做from numpy import * 实际上是一个非常坏主意。您将覆盖内置函数,例如 sumabs...

    HTH!

    【讨论】:

    • 谢谢!来自matlab,仍然有很多关于python行为的知识:)这个答案和@Andrey Sobolev的答案正是我想要的。 item_a 只是为了获取数组的值,但实际上不需要,因为它是我感兴趣的索引
    【解决方案2】:

    如果你想要单线,那么你可以使用

    item_c=item_a[(date_a >= (datetime(2000,1,3))) * (date_a <= (datetime(2000,1,4)))]
    

    【讨论】:

    • 太棒了,正是我正在寻找的!谢谢:)
    • 仅供参考:&amp;* 更易读,在这里,它的作用完全相同。
    【解决方案3】:

    我认为使用 List Comprehension 的以下内容应该适合您

    [item_a[i] for i in xrange(0,len(date_a)) if date_a[i] >= (datetime(2000,1,3)) and date_a[i] <= (datetime(2000,1,4))]
    

    选择range 0 &lt;= i &lt; length of date_a where datetime(2000,1,3) &lt;= date_a[i] &lt;= datetime(2000,1,4)内item_a中的所有项目

    【讨论】:

    • 像魅力一样工作!由于数据集非常大,我试图避免循环,但我也会测试这个实现。
    猜你喜欢
    • 2018-03-02
    • 2021-11-28
    • 2023-03-08
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    相关资源
    最近更新 更多