大小为(100,1)和(100,)的numpy数组有什么区别?

2024-03-28 11:12:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

而另一个b是:

^{2}$

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

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. 我怎么解决这个问题?在

Tags: the函数fromimportnumpystats方式scipy
3条回答

您需要在第一个数组上调用resheme函数.reshape((100,1))resheme将更改np数组的“shape”属性,这将使1D数组[1,2,3,…,100]变成2D数组[[1],[2],[3],…[100]]

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

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

第一个问题的答案: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

相关问题 更多 >