Extract items from array: between given values/conditions

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

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!

--------------Solutions-------------

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's not clear to me why you are using the item_a variable. But to isolate the entries you want you can simply do:

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

The resulting indexes are zero-based, so they correspond to the third and fourth element of your array.

EDIT: np is due to import numpy as np. Doing from numpy import * is in fact a very bad idea. You will overwrite built in functions such as sum and abs for example...

HTH!

I think the following should work for you using 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))]

Select all items in item_a within range 0 <= i < length of date_a where datetime(2000,1,3) <= date_a[i] <= datetime(2000,1,4)

Category:python Time:2011-11-30 Views:0

Related post

  • PHP I have two arrays, I want to extract items from Array 1 if it's not already in Array 2 2011-02-13

    Like the title says, I have two arrays and I just want to get everything from the first array that's not already in the second array. How do I do this? --------------Solutions------------- Use array_diff: $array1 = array("a" => "green", "red", "bl

  • Checking item of array on "undefined" in JavaScript 2012-02-18

    My JS-code has array arrayResults, some element of him can be "undefined" - this is feature of algorithm. To check that there is no such elements I use the follow code: for (i in arrayResults) { if (typeof(arrayResults[i])=='undefined') { // ask user

  • C# How do I append the previous item in array to the next item in the array for unknown number of items? 2009-01-03

    How do I append the previous item in array to the next item in the array for unknown number of items? Here is what I'm trying to do. I have a string containing an LDAP path such as "OU=3,OU=2,OU=1,DC=Internal,DC=Net", I want to create each container

  • Returning first x items from array 2009-10-15

    I want to return first 5 items from array. How can I do this? --------------Solutions------------- array_slice returns a slice of an array $sliced_array = array_slice($array, 0, 5) is the code you want in your case to return the first five elements a

  • What is the best way to get the first item from an iterable matching a condition? 2010-03-02

    In Python, I would like to get the first item from a list matching a condition. For example, the following function is adequate: def first(the_iterable, condition = lambda x: True): for i in the_iterable: if condition(i): return i This function could

  • Android itemized overlay Array slowing down 2010-07-16

    I've got a script which gets data from a MySQL database through an http request, puts it into a json array, then puts each item into an itemized overlay array so that each item can be put onto a map. Problem is, it takes > 5 minutes to load all th

  • Insert new item in array on any position in PHP 2010-09-26

    How can I insert a new item into an array on any position, for example in the middle of array? --------------Solutions------------- You may find this a little more intuitive. It only requires one function call to array_splice: $original = array( 'a',

  • Total Nos. of items in array variable 2010-10-14

    I have an array variable (string type). It contains certain no. of items, that I donot know how many they are. I need to run a loop for that many nos. that the array contains. I tried LBound and UBound loop but it says my array is not a system array.

  • Remove array items with Array.FindAll 2010-10-24

    How can I remove an item in an array? This is what I have, which is not OK. // fr_watchdog.items = public array string numToRemove = "test"; fr_watchdog.items = Array.FindAll(fr_watchdog.items, val => val != numToRemove).ToArray(); All done. I hav

  • Deleting an item from array 2010-11-15

    class ArrayApp{ public static void main(final String[] args){ long[] arr; // reference to array arr = new long[100]; // make array int nElems = 0; // number of items int j; // loop counter long searchKey; // key of item to search for // -------------

  • php search array for string, then if found, move that string to first item of array 2011-03-28

    so let's say i have an array: $people[0] = "Bob"; $people[1] = "Sally"; $people[2] = "Charlie"; $people[3] = "Clare"; if (in_array("Charlie", $people)) { //move Charlie to first item in array } What would be the most efficient way to get Charlie to t

  • Scrapy - parse a page to extract items - then follow and store item url contents 2011-04-28

    I have a question on how to do this thing in scrapy. I have a spider that crawls for listing pages of items. Every time a listing page is found, with items, there's the parse_item() callback that is called for extracting items data, and yielding item

  • Removing item from array by value in JavaScript giving unpredictable results 2011-05-22

    I have this code for removing an item from an array by value in JS... function remove_item(index){ //log out selected array console.log('before >> ' + selected); // //log out item that has been requested to be removed console.log('removing >

  • insert item into array 2011-08-11

    I have a result array that comes back from CodeIgniter looking like this: Array ( [ILS] => ils [0] => Array ( [laser_id] => 1 [sort_order] => 1 [laser_name] => ILS12.75 [laser] => ils1275 [image] => ils1275 [link] => ils1275 )

  • C# MessageBox For All Items In Array 2011-09-18

    I am trying to iterate through an array of strings and present all of them in a single messagebox. The code I have at the minute is this: string[] array = {"item1", "item2", "item3"}; foreach(item in array) { MessageBox.Show(item); } This obviously b

  • MongoDB remove item from array from a selected document 2011-11-16

    I am developing a web app using Codeigniter and Alex Bilbies MongoDB library. Each user got a document that contains an item called phones which contains an array of phone numbers. How can I pull an item out of the array from the selected users docum

  • JSON:PP only encodes first item in array 2011-11-28

    I'm pushing my values into the array... while ( ... ) { push @array, { label => "label", value => "value" }; } This appears to be working. Then... use JSON::PP ; print JSON::PP->new->utf8->encode(@array) ; only generates... {"value":"v

  • How to find item in Array objects 2012-02-17

    I am having array objects in jquery in which has n number of items array={id:1, name:x}; array={id:2, name:y}; array={id:3, name:z}; . . . . array={id:n, name:n}; Now I have to find particular item in this array object since i dont know the index of

  • How to remove item from array object in jquery 2012-02-20

    How to remove item from jquery array object. I used splice method as follows. But it slice next item of array[i]. $.each(array, function (i, item) { var user = array[i]; jQuery.each(array2, function (index, idata) { debugger if (idata.Id == user.User

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.272 (s). 13 q(s)