[Tutor] Subtract a 1D Array from a 2D Array

Stephen P. Molnar s.molnar at sbcglobal.net
Sat May 13 12:59:19 EDT 2017


On 05/13/2017 11:16 AM, eryk sun wrote:
> 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.
>

That solved the problem.

Many thanks.

-- 
Stephen P. Molnar, Ph.D.		Life is a fuzzy set
www.molecular-modeling.net		Stochastic and multivariate
(614)312-7528 (c)
Skype: smolnar1


More information about the Tutor mailing list