Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use the dimensions of a numpy array as an if-statement python

I will loop through different numpy arrays. Some will be 2D, some will be 1D. If the assessed array is 1D, I will want to tile it into a 2D array. Example:

c = {'a': np.array([1, 2, 3]), 'b' : np.array([[1, 2, 3], [4, 5, 6]])}

for k in c:
    if c[k].shape #is 1D:
        c[k] = np.tile(c[k], (len(c[k]),1))

I don't know how to run that condition. Any ideas? I have tried things like

aa = np.array([1, 2, 3])
aa.shape[0]
# 3
aa.shape[1]
# Gives an out of range error

I guess it would be possible to find out it is a 1D array by finding there isn't a second dimension. But I don't know how to code this in an if-statement.

Thanks

like image 663
Cristian FL Avatar asked Feb 17 '26 12:02

Cristian FL


1 Answers

NumPy arrays have an attribute called ndim, which represents exactly what you think it does: the number of the array's dimensions. So, you can do this:

if c[k].ndim == 1:
    # do something
like image 183
ForceBru Avatar answered Feb 20 '26 00:02

ForceBru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!