Given a numpy array structure of identical (user specified) objects, is there a way to references all of them at once?
E.g. given a numpy array structure of objects of type date, is there a way to take the average of the years without resorting to a for loop or to +1 to the year attribute of each object in the array?
Example code follows.
from numpy import *
from datetime import *
#this works
A = array([2012, 2011, 2009])
print average(A)
date1 = date(2012,06,30)
date2 = date(2011,06,30)
date3 = date(2010,06,30)
B = array([date1, date2, date3])
print B[0].year
print B[1].year
print B[2].year
#this doesn't
print average(B.year)
You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.
Size of the first dimension of the NumPy array: len() len() is the Python built-in function that returns the number of elements in a list or the number of characters in a string.
NumPy arrays are typed arrays of fixed size. Python lists are heterogeneous and thus elements of a list may contain any object type, while NumPy arrays are homogenous and can contain object of only one type.
Think you can do this the following way:
from numpy import array, average
from datetime import date
date1 = date(2012,06,30)
date2 = date(2011,06,30)
date3 = date(2010,06,30)
B = array([date1, date2, date3])
avYear = average([x.year for x in B])
EDITED as per comment:
B = array([x.replace(year=x.year+10) for x in B])
And note that using from module import * is not very good - it is always better to import only thoose classes and functions which you really need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With