代码之家  ›  专栏  ›  技术社区  ›  normanius

如何确保numpy数组是二维行向量或列向量?

  •  2
  • normanius  · 技术社区  · 6 年前

    有没有 numpy 函数确保一维或二维数组是列向量还是行向量?

    例如,我有以下向量/列表之一。将任何输入转换为列向量的最简单方法是什么?

    x1 = np.array(range(5))
    x2 = x1[np.newaxis, :]
    x3 = x1[:, np.newaxis]
    
    def ensureCol1D(x):
        # The input is either a 0D list or 1D.
        assert(len(x.shape)==1 or (len(x.shape)==2 and 1 in x.shape))
        x = np.atleast_2d(x)
        n = x.size
        print(x.shape, n)
        return x if x.shape[0] == n else x.T
    
    assert(ensureCol1D(x1).shape == (x1.size, 1))
    assert(ensureCol1D(x2).shape == (x2.size, 1))
    assert(ensureCol1D(x3).shape == (x3.size, 1))
    

    而不是写我自己的函数 ensureCol1D ,是否有类似的东西已经在 麻木的 确保向量是列?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Primusa    6 年前

    您的问题本质上是如何将数组转换为“列”,列是行长度为1的二维数组。这可以用 ndarray.reshape(-1, 1) .

    这意味着你 reshape 数组的行长度为1,并让numpy推断行数/列长度。

    x1 = np.array(range(5))
    print(x1.reshape(-1, 1))
    

    输出:

    array([[0],
       [1],
       [2],
       [3],
       [4]])
    

    重新整形时得到相同的输出 x2 x3 . 此外,这也适用于N维阵列:

    x = np.random.rand(1, 2, 3)
    print(x.reshape(-1, 1).shape)
    

    输出:

    (6, 1)
    

    最后,这里唯一缺少的就是您做出了一些断言,以确保不能转换的数组不会被错误地转换。您要做的主要检查是形状中非一个整数的数目小于或等于一。这可以通过以下方式实现:

    assert sum(i != 1 for i in x1.shape) <= 1
    

    这张支票和 .reshape 让我们将逻辑应用于所有numpy数组。