Home > Software engineering >  Similar to numpy arange
Similar to numpy arange

Time:05-30

Started with NumPy recently, want to make an array of specific kind. I can make these arrays using normal logic but want to know if same thing can be done with NumPy just for learning:

arr_1 = [[0,2],[4,6],[8,10],[12,14]]
arr_2 = [[2,4],[6,8],[10,12],[14,16]]

I looked at NumPy arange, but am looking for some other alternative. I first created a range, then splitted them in array with steps. Looking for some other approach with NumPy.

CodePudding user response:

I would create

arr_1 = [[0,2],[4,6],[8,10],[12,14]]
arr_2 = [[2,4],[6,8],[10,12],[14,16]]

following way

import numpy as np
arr_1 = np.arange(0,15,2).reshape(-1,2)
arr_2 = np.arange(2,17,2).reshape(-1,2)
print(arr_1)
print(arr_2)

output

[[ 0  2]
 [ 4  6]
 [ 8 10]
 [12 14]]
[[ 2  4]
 [ 6  8]
 [10 12]
 [14 16]]

Explanation: I use arange in 3-arguments form (start, stop, step) then .reshape with -1,2 which tells numpy that 2nd dimension value should be 2 and 1st dimension should be computed based on number of elements in ndarray.

CodePudding user response:

import numpy as np

res1 = 2 * np.arange(8).reshape((4, -1))
res2 = 2 * np.arange(1, 9).reshape((4, -1))
  • Related