Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing object methods in numpy.where?

Tags:

python

date

numpy

I have data in a numpy array (read from a .csv file). The relevant extract from np.genfromtxt is:

dtype = [("Category", "|S10"),
         ("Status", "|S11"),
         ("Date_start", object),
         ("Date_stop", object)],
names=True,
converters={2:lambda d:datetime.strptime(d, "%d/%m/%y"),
            3:lambda d:datetime.strptime(d, "%d/%m/%y")}
)

Everything works with one exception — accessing elements of the datetime objects. The following two lines of code return exactly what I expect:

print inp['Date_start'][1].month #returns 7
print np.where(inp['Category'] == '"R5"') #returns an array of matching indices

but the following line of code throws an AttributeError: 'numpy.ndarray' object has no attribute 'month'

print np.where(inp['Date_start'].month == 7)

This means I can't return results based on which month things occurred in, which I need to.

Is there any way to get the behaviour I want from np.where?

like image 409
cms_mgr Avatar asked Dec 13 '25 04:12

cms_mgr


1 Answers

You could define a vectorized attribute getter:

def func(a):
    return a.month

vfunc = np.vectorize(func)

and then use:

np.where(vfunc(inp['Date_start']) == 7)
like image 159
user545424 Avatar answered Dec 15 '25 17:12

user545424