【问题标题】:What is the difference between a numpy array of size (100, 1) and (100,)?大小为 (100, 1) 和 (100,) 的 numpy 数组有什么区别?
【发布时间】:2019-07-31 15:18:39
【问题描述】:

我有两个来自不同函数的变量,第一个 a 是:

<class 'numpy.ndarray'>
(100,)

而另一个b是:

<class 'numpy.ndarray'>
(100, 1)

如果我尝试通过以下方式关联它们:

from scipy.stats import pearsonr
p, r= pearsonr(a, b)

我明白了:

    r = max(min(r, 1.0), -1.0)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我的问题是:

  1. a 和 b 有什么区别?
  2. 我该如何解决这个问题?

【问题讨论】:

标签: python numpy


【解决方案1】:

(100,1) 是长度为 1 的二维数组,例如 = [[1],[2],[3],[4]],第二个是一维数组 [1, 2, 3, 4 ]

a1 = np.array([[1],[2],[3],[4]])
a2 = np.array([1, 2, 3, 4 ])

【讨论】:

    【解决方案2】:

    第一个问题的答案a是一个向量,b是一个矩阵。查看此 stackoverflow 链接了解更多详情:Difference between numpy.array shape (R, 1) and (R,)

    第二个问题的答案

    我认为将一种形式转换为另一种形式应该可以正常工作。对于您提供的函数,我猜它需要向量,因此只需使用 b = b.reshape(-1) 重塑 b 即可将其转换为单个维度(向量)。请看以下示例以供参考:

    >>> import numpy as np
    >>> from scipy.stats import pearsonr
    >>> a = np.random.random((100,))
    >>> b = np.random.random((100,1))
    >>> print(a.shape, b.shape)
    (100,) (100, 1)
    >>> p, r= pearsonr(a, b)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\Users\xyz\Appdata\Local\Continuum\Anaconda3\lib\site-packages\scipy\stats\stats.py", line 3042, in pearsonr
        r = max(min(r, 1.0), -1.0)
    ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
    >>> b = b.reshape(-1)
    >>> p, r= pearsonr(a, b)
    >>> print(p, r)
    0.10899671932026986 0.280372238354364
    

    【讨论】:

      【解决方案3】:

      您需要将第一个上的 reshape 函数调用为 .reshape((100,1)) Reshape 将更改 np 数组的“shape”属性,这将使一维数组 [1,2,3, ..., 100 ] 到二维数组 [[1],[2],[3],...[100]]

      【讨论】:

      • 为了提供更好的答案,您应该解释原因。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-14
      • 2020-06-26
      • 1970-01-01
      • 2011-10-11
      • 1970-01-01
      • 2013-07-04
      相关资源
      最近更新 更多