使用 numpy 数组的维度作为 if 语句 python

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

我将遍历不同的 numpy 数组。有些是二维的,有些是一维的。如果评估的数组是一维的,我会想把它平铺成一个二维数组。 示例:

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

我不知道如何运行那个条件。有任何想法吗? 我尝试过

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

我想如果发现没有第二维,就可以确定它是一维数组。但我不知道如何在 if 语句中对此进行编码。

谢谢

您需要检查 array.shape 有多少个元素。因此,您可以通过 运行 以下

检查一维数组
if len(c[k].shape) == 1

NumPy 数组有一个名为 ndim 的属性,它准确地表示了您认为它的作用:数组的维数。所以,你可以这样做:

if c[k].ndim == 1:
    # do something

你可以做到

if len(aa.shape)==1:
   # something

dir has always helped me, esp when dealing with not so well documented interfaces. Unlike ndarray.

dir(np.array([]))

['T', '__abs__', '__add__', '__and__', '__array__', '__array_finalize__', '__array_interface__', '__array_prepare__', '__array_priority__', '__array_struct__', '__array_wrap__', '__class__', '__complex__', '__contains__', '__copy__', '__deepcopy__', '__delattr__', '__delitem__', '__delslice__', '__div__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__hex__', '__iadd__', '__iand__', '__idiv__', '__ifloordiv__', '__ilshift__', '__imod__', '__imul__', '__index__', '__init__', '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__', '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__', '__len__', '__long__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__setitem__', '__setslice__', '__setstate__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__xor__', 'all', 'any', 'argmax', 'argmin', 'argpartition', 'argsort', 'astype', 'base', 'byteswap', 'choose', 'clip', 'compress', 'conj', 'conjugate', 'copy', 'ctypes', 'cumprod', 'cumsum', 'data', 'diagonal', 'dot', 'dtype', 'dump', 'dumps', 'fill', 'flags', 'flat', 'flatten', 'getfield', 'imag', 'item', 'itemset', 'itemsize', 'max', 'mean', 'min', 'nbytes', 'ndim', 'newbyteorder', 'nonzero', 'partition', 'prod', 'ptp', 'put', 'ravel', 'real', 'repeat', 'reshape', 'resize', 'round', 'searchsorted', 'setfield', 'setflags', 'shape', 'size', 'sort', 'squeeze', 'std', 'strides', 'sum', 'swapaxes', 'take', 'tobytes', 'tofile', 'tolist', 'tostring', 'trace', 'transpose', 'var', 'view']