Skip to content

Tag: numpy

UserWarning: converting a masked element to nan

Executing a python script (way to long to include here) I wrote leads to a warning message. I don’t know at which line in my code this gets raised. How can I get this information? Furthermore, what does this mean exactly? In fact, I didn’t know I was using a masked array of some sort? Answer You c…

Correct way to generate random numbers in Cython?

What is the most efficient and portable way to generate a random random in [0,1] in Cython? One approach is to use INT_MAX and rand() from the C library: Is it OK to use INT_MAX in this way? I noticed that it’s quite different from the constant you get from Python’s max int: yields: Which is the r…

Averaging over every n elements of a numpy array

I have a numpy array. I want to create a new array which is the average over every consecutive triplet of elements. So the new array will be a third of the size as the original. As an example: should return the array: Can anyone suggest an efficient way of doing this? I’m drawing blanks. Answer If your …

Reversed array in numpy?

Numpy tentative tutorial suggests that a[ : :-1] is a reversed a. Can someone explain me how we got there? I understand that a[:] means for each element of a (with axis=0). Next : should denote the number of elements to skip (or period) from my understanding. Answer As others have noted, this is a python slic…

Check if variable is defined with Numpy array?

Sometimes I have a situation where I want to test whether a variable is 0 or None or not. In pure Python, this is simply but when foo is possibly a Numpy object (such as numpy.ndarray), this does not work anymore and I get the error: and in this case I want a.any(), however this fails on non-iterable objects.…