[Tutor] Subtract a 1D Array from a 2D Array
eryk sun
eryksun at gmail.com
Sat May 13 11:16:06 EDT 2017
On Sat, May 13, 2017 at 1:33 PM, Stephen P. Molnar
<s.molnar at sbcglobal.net> wrote:
> I am using Python 3.6 in Anaconda3 Spyder IDE.
>
> I have two arrays:
>
> X Y Z
> a
> 0 0 0
> 2.059801 0 0
> -1.203126 3.402953 0
> -1.108639 -1.567853 2.715601
> -0.938564 -1.32733 -2.299003
> a_c
> 0.4283375 0.91755 0.208299
>
> and want to subtract the value of the value of each column or the array a_c
> from the each value in the corresponding column of array c.
>
> Trying a_mm = a - a_c where a_mm is the new array results in the error
> message:
>
> ValueError: operands could not be broadcast together with shapes (3,5) (1,3)
>
> My search for a solution has not been successful.
You've presented array `a` as if it's 5x3, but the error says it's
3x5. If it were actually 5x3, there would be no problem:
import numpy as np
a = np.array([[0, 0, 0],
[2.059801, 0, 0],
[-1.203126, 3.402953, 0],
[-1.108639, -1.567853, 2.715601],
[-0.938564, -1.32733, -2.299003]])
a_c = np.array([[0.4283375, 0.91755, 0.208299]])
>>> a.shape
(5, 3)
>>> a_c.shape
(1, 3)
>>> a - a_c
array([[-0.4283375, -0.91755 , -0.208299 ],
[ 1.6314635, -0.91755 , -0.208299 ],
[-1.6314635, 2.485403 , -0.208299 ],
[-1.5369765, -2.485403 , 2.507302 ],
[-1.3669015, -2.24488 , -2.507302 ]])
You can use the transpose of either array. For example, use `a.T` to
get the same number of columns, or use `a_c.T` to get the same number
of rows.
More information about the Tutor
mailing list