Zanam
Zanam

Reputation: 4807

python using multiple conditions with numpy where

I have a giant array called AllDays storing datetime.

I generated an array which stores day of week information for each day.

I am trying to extract the weekends only from the original datetime array AllDays.

So, from the day of week I am trying the following:

DayOfWeek = np.asarray([x.weekday() for x in AllDays])
#AllDays stores datetime objects
ind = np.where(DayOfWeek == 0 or DayOfWeek == 6) #gives Error

I aim to use it as following to extract only the weekends:

weekends = AllDays[ind]

Error at line

ind = np.where(DayOfWeek == 0 or DayOfWeek == 6)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Upvotes: 0

Views: 362

Answers (1)

Stephan W.
Stephan W.

Reputation: 188

The problem here is the "or" which is not defined for numpy boolean arrays. You can just use a sum instead:

np.where((DayOfWeek == 0) + (DayOfWeek == 6))

edit: You can also use the bitwise or operator:

np.where((DayOfWeek == 0) | (DayOfWeek == 6))

which gives the same result but is somewhat nicer as we are working with booleans...

Upvotes: 2

Related Questions