2017-12-27 1262 views
0

我想做一些類似於以下R代碼numpy,其中y是回收利用。如何在兩個numpy陣列的尺寸不匹配時回收元素?

R> x=rbind(c(1,2,3), c(4,5,6)) 
R> y=c(1,2) 
R> x/y 
    [,1] [,2] [,3] 
[1,] 1 2.0 3 
[2,] 2 2.5 3 

顯然,以下代碼不適用於numpy。有人知道什麼是可用的等效Python代碼嗎?謝謝。

>>> x=numpy.array([[1,2,3], [4, 5, 6]]) 
>>> y=numpy.array([1,2]) 
>>> x/y 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: operands could not be broadcast together with shapes (2,3) (2,) 
+0

你能解釋一下R代碼在幹什麼嗎? – Divakar

+0

它將'x'的每一列用'y'分開。 – user1424739

+0

問題的標題有點令人困惑 - 「回收y」是什麼意思? –

回答

1

如何

x=numpy.array([[1,2,3], [4, 5, 6]]) 
y=numpy.array([1,2]) 
x/y[:, None] 

y[:, None]接通(2,)陣列到陣列(2,1),從而允許分割的廣播與x

+0

此功能在哪裏記錄? – user1424739

+0

@ user1424739 https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html – Divakar

+0

@ user1424739另一個信息來源是:https://docs.scipy.org/doc/ numpy-1.13.0/reference/arrays.indexing.html請注意,'y [:,None]'相當於'y [:, numpy.newaxis]'。 –