6

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)

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your quick reply! I would appreciate it very much if you could also consider the following. How to subtract 10 years from each of the year attributes (2012,2011,2010) and store the new values in the same objects (of the structure B)?
@rm check my addition within answer whether it helps you or not
Thanks for the update! Could you please clarify one detail? Does the line “[x.replace(year=x.year+10) for x in B]” create new copies of the date objects or does it manipulate the original ones? After some testing it seems to me that it creates a new list with copies of the original date objects.
@rm as far as i know date object is not mutable, when i try to assign new value to year property it throwing an exception about read-only property editing. However think that you can update your code to store date values as a strings and handle(convert to date) them when needed.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.