0

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()
2
  • 1
    You could define a variable weekend_indexes = (0, 6) and check DayOfWeek in weekend_indexes. Then you'd have a single condition to put in your np.where() Commented Jun 3, 2016 at 13:48
  • The ValueError comes up frequently. It indicates that an array is being used in a context that expects a scalar True/False (e.g. the or). Commented Jun 3, 2016 at 16:11

1 Answer 1

2

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...

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

4 Comments

The element-wise OR operator is |. np.where((DayOfWeek == 0) | (DayOfWeek == 6))
Yeah, that is even nicer. Thanks!
because true + true = true does not really make sense as far as logics are concerned. In the implementation, it works just as good.
The () are equally important. You want to evaluate the == first.

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.