2

Goodmorning to all, I have a column vector

vec=np.array([15.1,7.9,4.5,12.8,10.5],ndmin = 2)   

and a matrix

mt = np.matrix([[1,35.5,1.23],[1,40.8,1.89],[1,30.2,1.55],[1,4.3,1.18], [1,10.7,1.68]])    

if I try to subtract the vectore and the matrix like

 np.subtract(vec,mt)

the result is mathematically wrong:

array([[ 14.1 , -20.4 ,  13.87],
       [  6.9 , -32.9 ,   6.01],
       [  3.5 , -25.7 ,   2.95],
       [ 11.8 ,   8.5 ,  11.62],
       [  9.5 ,  -0.2 ,   8.82]])

all mt's columns' values are subtracted, instead of just the first I'd like to get this result

array([[ 14.1  , 35.5 ,  1.23],
       [ 6.9  , 40.8 ,  1.89],
       [ 3.5  , 30.2 ,  1.55],
       [ 11.8  ,  4.3 ,  1.18],
       [ 9.5  , 10.7 ,  1.68]])

how can I fix that? thanks to all :)

3
  • vec_mt = np.substract(vec,mt[0])? Commented Aug 9, 2019 at 11:24
  • 1
    thanks to all for the replies. I add that is easily possible to do that with Pandas. vec=pd.Series([15.1,7.9,4.5,12.8,10.5]) SeG=pd.DataFrame({'const':[1,1,1,1,1], 'growth':[35.5, 40.8, 30.2, 4.3, 10.7], 'dim':[1.23, 1.89, 1.55, 1.18, 1.68]}) a['const']=vec-a['const'] Commented Aug 9, 2019 at 13:17
  • Are you sure np.subtract(vec,mt) ran? It raises an error for me. Commented Aug 9, 2019 at 17:12

2 Answers 2

2

Slice and subtract -

  • T attribute is the transpose of the array.

Ex.

import numpy as np

vec=np.array([15.1,7.9,4.5,12.8,10.5],ndmin = 2)
mt = np.matrix([[1,35.5,1.23],[1,40.8,1.89],[1,30.2,1.55],[1,4.3,1.18], [1,10.7,1.68]])

mt[..., 0] = vec.T - mt[..., 0]
#or
#mt.T[0] = np.subtract(vec, mt.T[0])

print(mt)

O/P:

[[14.1  35.5   1.23]
 [ 6.9  40.8   1.89]
 [ 3.5  30.2   1.55]
 [11.8   4.3   1.18]
 [ 9.5  10.7   1.68]]
Sign up to request clarification or add additional context in comments.

Comments

1

You commented that the pandas version is easy. So is the numpy one, if you use the right starting point.

In [110]: vec=pd.Series([15.1,7.9,4.5,12.8,10.5]) 
     ...: SeG=pd.DataFrame({'const':[1,1,1,1,1], 'growth':[35.5, 40.8, 30.2, 4.3, 10.7], 'dim':[1.23, 1.89, 1
     ...: .55, 1.18, 1.68]})                                                                                 
In [111]: vec                                                                                                
Out[111]: 
0    15.1
1     7.9
2     4.5
3    12.8
4    10.5
dtype: float64
In [112]: SeG                                                                                                
Out[112]: 
   const  growth   dim
0      1    35.5  1.23
1      1    40.8  1.89
2      1    30.2  1.55
3      1     4.3  1.18
4      1    10.7  1.68

vec is a Series, its values is a 1d array. Same for one column of SeG:

In [113]: vec.values                                                                                         
Out[113]: array([15.1,  7.9,  4.5, 12.8, 10.5])
In [114]: SeG['const']                                                                                       
Out[114]: 
0    1
1    1
2    1
3    1
4    1
Name: const, dtype: int64
In [115]: SeG['const'].values                                                                                
Out[115]: array([1, 1, 1, 1, 1])

So a['const']=vec-a['const'] amounts to subtracting one 1d array from another and putting the result back in the right place. That's exactly what the accepted answer does:

mt[..., 0] = vec.T - mt[..., 0]

Lets start with 2 arrays, one is 1d, the other 2d (but not the np.matrix subclass):

In [116]: x=np.array([15.1,7.9,4.5,12.8,10.5])                                                               
In [117]: y = np.array([[1,35.5,1.23],[1,40.8,1.89],[1,30.2,1.55],[1,4.3,1.18], [1,10.7,1.68]])

In [118]: y[:,0] = x - y[:,0]                                                                                
In [119]: y                                                                                                  
Out[119]: 
array([[14.1 , 35.5 ,  1.23],
       [ 6.9 , 40.8 ,  1.89],
       [ 3.5 , 30.2 ,  1.55],
       [11.8 ,  4.3 ,  1.18],
       [ 9.5 , 10.7 ,  1.68]])

===

With your original arrays:

In [103]: vec                                                                                                
Out[103]: array([[15.1,  7.9,  4.5, 12.8, 10.5]])  # (1,5) shape
In [104]: mt                                                                                                 
Out[104]: 
matrix([[ 1.  , 35.5 ,  1.23],
        [ 1.  , 40.8 ,  1.89],
        [ 1.  , 30.2 ,  1.55],
        [ 1.  ,  4.3 ,  1.18],
        [ 1.  , 10.7 ,  1.68]])     # (5,3) shape
In [105]: vec.T                                                                                              
Out[105]: 
array([[15.1],
       [ 7.9],
       [ 4.5],
       [12.8],
       [10.5]])           # (5,1) shape
In [106]: mt[:,0]                                                                                            
Out[106]: 
matrix([[1.],
        [1.],
        [1.],
        [1.],
        [1.]])            # (5,1) shape

If mt as ndarray instead of matrix, mt[:,0] would have a (5,) shape. That distinction is important.

In [107]: mt[:,0] = vec.T-mt[:,0]          # operation on (5,1) arrays

Your subtract(vec, mt) should have given you an error, not just an undesired result. vec is (1,5) shape, mt is (5,3). Those aren't compatible:

In [122]: np.subtract(_103, _104)                                                                            
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-122-35bafa7d9625> in <module>
----> 1 np.subtract(_103, _104)

ValueError: operands could not be broadcast together with shapes (1,5) (5,3) 

1 Comment

Thanks for the useful answer. Yes, I noticed that ndarray instead of matrix matters for the shape because when I was trying some commands it raised the error you posted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.