Home > Back-end >  numpy - how to increment by one all values on axis 1
numpy - how to increment by one all values on axis 1

Time:09-30

I would like to increment all values on axis 1 by one.

For instance, row[0] col[0] increases by 1, row[1] col[0] by 2, and so on...

Example of how to do this with a single-dimensional array:

y = np.random.random(size=(10,))
y  = np.arange(start=1, stop=11, step=1)

result:

[ 1.66704813  2.90625487  3.961399    4.64969495  5.5286593   6.31736865
  7.24056032  8.25632077  9.02458071 10.1816335 ]

Now I have a multi-dimensional array I would like to do the same as above only by columns

y = np.random.random(size=(10,3))
y  = np.arange(start=1, stop=11, step=1)  # Not going to work. Need each col to grow by one each row increment. like the single-dimensional array only by column.

end result is something like:

[[1.66704813 1.90625487 1.961399  ]
 [2.64969495 2.5286593  2.31736865]
 [3.24056032 3.25632077 3.02458071]
 [4.1816335  4.13044436 4.13969493]
 [5.48485214 5.58980863 5.59890548]
 [6.58126238 6.30004674 6.730429  ]
 [7.76121817 7.94366992 7.1039714 ]
 [8.81874117 8.00239219 8.16807975]
 [9.64509574 9.75334071 9.59641831]
 [10.11176155 10.71027095 10.77104173]]

CodePudding user response:

Expand the result of np.arange as a column vector:

>>> y
array([[0.0191932 , 0.30157482, 0.66017354],
       [0.29007761, 0.61801543, 0.4287687 ],
       [0.13547406, 0.29828233, 0.56996491],
       [0.59087276, 0.57432525, 0.65320082],
       [0.65210327, 0.43141844, 0.8965466 ],
       [0.36756187, 0.43586493, 0.89192336],
       [0.80619399, 0.70388858, 0.10022689],
       [0.91948261, 0.7142413 , 0.99884701],
       [0.1494483 , 0.86812606, 0.16249293],
       [0.61555956, 0.12381998, 0.84800823]])
>>> y   np.arange(1, 11)[:, None]
array([[ 1.0191932 ,  1.30157482,  1.66017354],
       [ 2.29007761,  2.61801543,  2.4287687 ],
       [ 3.13547406,  3.29828233,  3.56996491],
       [ 4.59087276,  4.57432525,  4.65320082],
       [ 5.65210327,  5.43141844,  5.8965466 ],
       [ 6.36756187,  6.43586493,  6.89192336],
       [ 7.80619399,  7.70388858,  7.10022689],
       [ 8.91948261,  8.7142413 ,  8.99884701],
       [ 9.1494483 ,  9.86812606,  9.16249293],
       [10.61555956, 10.12381998, 10.84800823]])

Another option is to use np.random.uniform to directly generate results:

>>> np.random.uniform(np.arange(1, 11)[:, None], np.arange(2, 12)[:, None], (10, 3))
array([[ 1.22741463,  1.25435648,  1.05802916],
       [ 2.43441663,  2.31179588,  2.69634349],
       [ 3.37775184,  3.17960368,  3.02467873],
       [ 4.06724963,  4.67939277,  4.45369684],
       [ 5.53657921,  5.89667129,  5.99033895],
       [ 6.21689698,  6.6630782 ,  6.26332238],
       [ 7.020651  ,  7.75837865,  7.32001715],
       [ 8.38346389,  8.58831711,  8.83104846],
       [ 9.62898184,  9.87265066,  9.27354203],
       [10.79804683, 10.18563594, 10.95279166]])
  • Related