Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Object attributes within numpy array structure

Tags:

python

numpy

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)
like image 692
rm. Avatar asked Aug 16 '11 12:08

rm.


People also ask

How do you access the elements of a NumPy array?

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.

What attribute is used to retrieve the number of elements in an array NumPy?

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.

Can a NumPy array contain objects?

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.


1 Answers

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.

like image 106
Artsiom Rudzenka Avatar answered Nov 15 '22 01:11

Artsiom Rudzenka