python - Check number of columns numpy array that returns 1 if is a 1-dimensional array -


i have defined operations on 3xn numpy arrays, , want loop on each column of array. doing

for in range(nparray.shape[1]): 

however, if nparray.ndim == 1, fails. there clean way ascertain number of columns of numpy array, returns 1 if 1-dimensional array (like matlab's size operation does). otherwise, have implemented

if nparray.ndim == 1:     num_points = 1 else:     num_points = nparray.shape[1]  in range(num_points): 

if you're looking less verbose, this:

num_points = np.atleast_2d(nparray).shape[1] 

that will, of course, make new temporary array take shape, little silly… it'll pretty cheap, because it's view of same memory.

however, think explicit code more readable, except might try:

try:     num_points = nparray.shape[1] except indexerror:     num_points = 1 

if you're doing repeatedly, whatever do, should wrap in function. example:

def num_points(arr, axis):     try:         return arr.shape[axis]     except indexerror:         return 1 

then have write is:

for in range(num_points(nparray, 1)): 

and of course means can change things everywhere editing 1 place, e.g.,:

def num_points(arr, axis):     return nparray[:,...,np.newaxis].shape[1] 

Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -