从数组中提取项目:在给定的值/条件之间

从数组中提取项目:在给定的值/条件之间

问题描述:

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

I have a number of timeseries data in arrays and wish to extract values between given dates in the simplest way possible avoiding loops. Here's an example:

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(),但找不到解决方案.感谢您的帮助和指导!

Is there a one-line solution to this? I have looked at numpy any() and all(), and also where(), without being able to find a solution. I appreciate any help and point-in-direction!

如果您希望使用单线,则可以使用

If you want one-liner, then you can use

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