How to access Object attributes within numpy array structure
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 reso开发者_开发问答rting 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)
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.
This can be done via vectorize function.
import numpy as np
from datetime import date
date1 = date(2012,06,30)
date2 = date(2011,06,30)
date3 = date(2010,06,30)
B = np.array([date1, date2, date3])
yr = lambda x: x.year
vyr = np.vectorize(yr)
print vyr(B)
# array([2012, 2011, 2010])
print np.average(vyr(B))
# 2011.0
Note from the manual:
The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.
精彩评论