簡體   English   中英

大小為(100,1)和(100,)的numpy數組有什么區別?

[英]What is the difference between a numpy array of size (100, 1) and (100,)?

我有兩個變量在不同勢函數來了,第一個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. 我該如何解決?

(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鏈接以獲取更多詳細信息: numpy.array形狀(R,1)和(R,)之間的區別

第二個問題的答案

我認為將一種轉換為另一種形式應該可以正常工作。 對於您提供的功能,我想它需要矢量,因此只需使用b = b.reshape(-1)重塑b b = b.reshape(-1)將其轉換為單個尺寸(一個矢量)。 請看以下示例以供參考:

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

您需要在第一個調用reshape函數來調用.reshape((100,1))將更改np數組的“ shape”屬性,這將使一維數組[1,2,3,.. 。,100]到2D數組[[1],[2],[3],... [100]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM