Prev: Array construction | Next: Array indexing
import numpy as np
ar = np.arange(12) # constructs an array with successive integers in the range [0,11]
print(ar)
numpy.arange([start, ]stop [,step, dtype=None])
import numpy as np
ar = np.arange(10, 20, 2, dtype=float)
print(ar)
- shape: a tuple representing how the array member data are distributed over the array n-dimensions; for example a 16-member array can be of 2x8 or 1x16 or 4x4 or 2x2x2x2 shape
- ndim: dimensions (indices required to refer to an array member item)
- dtype: the type of array members, for example, int32, float64, etc.
- itemsize: size of each array member in memory in bytes
- size: lenght of the array (number of its members)
import numpy as np
ar = np.arange(3, 19, 3, dtype=int)
print(ar)
print(ar.shape, ar.ndim, ar.dtype.name, ar.itemsize, ar.size, type(ar), sep=', ')
import numpy as np
# Use 'reshape' method when creating the array to right away define its shape
ar = np.arange(16).reshape(2,8)
print(ar,'\n')
print(ar.ndim, ar.shape)
# Use 'reshape' to change the array shape as needed
ar = ar.reshape(2,2,4)
print(ar,'\n')
print(ar.ndim, ar.shape)
print()
import numpy as np
ar = np.arange(16).reshape(2,8)
ar.shape = (4,4)
print(ar)
print(ar.ndim, ar.shape,'\n')
ar.shape = (2,2,4)
print(ar)
print(ar.ndim, ar.shape)
- zeros(): generate an array full of zeros
- ones(): generate an array full of ones
- eye(): generate an array with '1's in diagonals
- linspace(): evenly distribute array values over a 'line'
import numpy as np
ar = np.zeros([3,5])
# it works the same if you use tuple
ar = np.zeros((2,4))
print(ar,'\n')
import numpy as np
br = np.ones((2,5))
print(br,'\n')
import numpy as np
dr = np.eye(4)
print(dr,'\n')
import numpy as np
er1 = np.linspace(start=1,stop=10,num=10,endpoint=True)
print(er1,'\n')
er2 = np.linspace(0,10,5,True)
print(er2,'\n')
er3 = np.linspace(0,10,5,False)
print(er3,'\n')
import numpy as np
ar = np.empty([2,20])
print(ar,'\n')
. Free learning material
. See full copyright and disclaimer notice