Home > Mobile >  How to multiply or divide (N, 50) numpy array with (N, 1) numpy array?
How to multiply or divide (N, 50) numpy array with (N, 1) numpy array?

Time:10-25

paths.shape
(525600, 50)

T.shape
(525600,)

how do I divide or multiply paths by T?

More specifically I want to do this

S = pd.DataFrame(paths)

d1 = S.divide(np.sqrt(T), axis=0)

but not using pandas

want to use numpy only

CodePudding user response:

2 arrays:

In [17]: paths = np.arange(12).reshape(4,3); T = np.arange(1,5)    
In [18]: paths.shape, T.shape
Out[18]: ((4, 3), (4,))            # not (4,1)

Your pandas approach:

In [19]: S = pd.DataFrame(paths)    
In [20]: d1 = S.divide(np.sqrt(T), axis=0)    
In [21]: S
Out[21]: 
   0   1   2
0  0   1   2
1  3   4   5
2  6   7   8
3  9  10  11

In [22]: d1
Out[22]: 
          0         1         2
0  0.000000  1.000000  2.000000
1  2.121320  2.828427  3.535534
2  3.464102  4.041452  4.618802
3  4.500000  5.000000  5.500000

That S.divide lets you specify an axis.

The wrong numpy:

In [23]: paths/np.sqrt(T)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [23], in <cell line: 1>()
----> 1 paths/np.sqrt(T)

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

But if we make T (4,1):

In [24]: paths/np.sqrt(T[:,None])
Out[24]: 
array([[0.        , 1.        , 2.        ],
       [2.12132034, 2.82842712, 3.53553391],
       [3.46410162, 4.04145188, 4.61880215],
       [4.5       , 5.        , 5.5       ]])

The key is broadcasting. Size 1 dimensions can be adjusted to match. Leading size 1 dimensions are automatic, but trailing ones are not. (n,) is a one element tuple (a basic Python expression). There isn't an implicit trailing size 1 dimension.

CodePudding user response:

There can be multiple different interpretations of your question, one of which may be related to this:

paths.transpose()*T
paths.transpose()/np.sqrt(T)
  • Related