How to multiply a scalar throughout a specific column within a NumPy array?

后端 未结 3 1516
死守一世寂寞
死守一世寂寞 2021-02-05 02:38

I need to do some analysis on a large dataset from a hydrolgeology field work. I am using NumPy. I want to know how I can:

  1. multiply e.g. the 2nd column of my ar

3条回答
  •  情话喂你
    2021-02-05 03:19

    To multiply a constant with a specific column or row:

    import numpy as np;
    X=np.ones(shape=(10,10),dtype=np.float64);
    X;
    
    ### this is our default matrix
    array([[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]])
    
    
    
     ## now say we want to multiple it with 10
    
     X=X*10;
    
    array([[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
       [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
       [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
       [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
       [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
       [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
       [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
       [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
       [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
       [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.]])
    
    ### Now if, we want to mulitply 3,5, 7 column with 5
    
    X[:,[3,5,7]]=X[:,[3,5,7]]*5
    
     array([[10., 10., 10., 50., 10., 50., 10., 50., 10., 10.],
       [10., 10., 10., 50., 10., 50., 10., 50., 10., 10.],
       [10., 10., 10., 50., 10., 50., 10., 50., 10., 10.],
       [10., 10., 10., 50., 10., 50., 10., 50., 10., 10.],
       [10., 10., 10., 50., 10., 50., 10., 50., 10., 10.],
       [10., 10., 10., 50., 10., 50., 10., 50., 10., 10.],
       [10., 10., 10., 50., 10., 50., 10., 50., 10., 10.],
       [10., 10., 10., 50., 10., 50., 10., 50., 10., 10.],
       [10., 10., 10., 50., 10., 50., 10., 50., 10., 10.],
       [10., 10., 10., 50., 10., 50., 10., 50., 10., 10.]])
    

    Similarly, we can do it for any columns. Hope it clarifies.

提交回复
热议问题