从数组中提取项目:在给定的值/条件之间 [英] Extract items from array: between given values/conditions

查看:91
本文介绍了从数组中提取项目:在给定的值/条件之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于从数组中提取项目:在给定的值/条件之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆