简体   繁体   中英

Python: efficient operations on numpy arrays

Say I have a numpy array x:

x = array([[  3,   2,   1],
           [  3,  25,  34],
           [ 33, 333,   3],
           [ 43,  32,   2]])

I want to carry out the following operations without explicitly writing a for loop ie say a method which uses automatic in built looping;

1) Replace the 2nd column by a column of all 1 ie

x = array([[  3,   1,   1],
           [  3,   1,  34],
           [ 33,   1,   3],
           [ 43,   1,   2]])

2) In the original array , replace 3rd column with the product of 2nd and 3rd ie

x = array([[  3,   2,   1*2],
           [  3,  25,  34*25],
           [ 33, 333,   3*333],
           [ 43,  32,   2*32]])

3) Finally, I would like to replace the 2nd column in the original array based on a condition ie

x[1] = 0  if x[0] > 5 else 4 

ie the array now looks like:

x = array([[  3,   4,   1],
           [  3,   4,  34],
           [ 33,   0,   3],
           [ 43,   0,   2]])

Any suggestions ? Thanks !

The documentation on numpy is well worth reading as this is fairly basic stuff...

  1. x[:,1] = 1
  2. x[:,2] *= x[:,1]
  3. x[:,1] = np.where( x[:,0] > 5, 0, 4 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM