Fix Python – extracting days from a numpy.timedelta64 value

I am using pandas/python and I have two date time series s1 and s2, that have been generated using the ‘to_datetime’ function on a field of the df containing dates/times.
When I subtract s1 from s2

s3 = s2 – s1

I get a series, s3, of type

timedelta64[ns]

0 385 days, 04:10:36
1 57 days, 22:54:00
2 642 days, 21:15:23
3 615 days, 00….

Fix Python – How to determine if a number is any type of int (core or numpy, signed or not)?

I need to test whether a variable is of type int, or any of np.int*, np.uint*, preferably using a single condition (i.e. no or).
After some tests, I guess that:

isinstance(n, int) will only match int and np.int32 (or np.int64 depending on plateform),
np.issubdtype(type(n), int) seems to match all int and np.int*, but doesn’t match np.uint*.

Thi….

Fix Python – Change values on matplotlib imshow() graph axis

Say I have some input data:
data = np.random.normal(loc=100,scale=10,size=(500,1,32))
hist = np.ones((32,20)) # initialise hist
for z in range(32):
hist[z],edges = np.histogram(data[:,0,z],bins=np.arange(80,122,2))

I can plot it using imshow():
plt.imshow(hist,cmap=’Reds’)

getting:

However, the x-axis values do not match the input data (i…..

Fix Python – Multiplying across in a numpy array

I’m trying to multiply each of the terms in a 2D array by the corresponding terms in a 1D array. This is very easy if I want to multiply every column by the 1D array, as shown in the numpy.multiply function. But I want to do the opposite, multiply each term in the row.
In other words I want to multiply:
[1,2,3] [0]
[4,5,6] * [1]
[7,8,9] [2]

a….

Fix Python – Shift elements in a numpy array

This question contains its own answer at the bottom. Use preallocated arrays.
Following-up from this question years ago, is there a canonical “shift” function in numpy? I don’t see anything from the documentation.
Here’s a simple version of what I’m looking for:
def shift(xs, n):
if n >= 0:
return np.r_[np.full(n, np.nan), xs[:-n]]
….