English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NumPy Array Creation

An ndarray array can be created in addition to using the underlying ndarray constructor in the following ways.

numpy.empty

The numpy.empty method is used to create an array with a specified shape(shape), data type(dtype), and uninitialized entries:

numpy.empty(shape, dtype = float, order = 'C')

Returns a new array with the given shape and type without initializing the entries.

Parameter

prototype - The shape of the empty array.dtype(optional) - The output data type required by the array, such as numpy.int8。Default value is numpy.float64.order(optional, default: 'C') - There are two options, "C" and "F", which represent row-major and column-major, respectively, the order in which elements are stored in computer memory.

Return value: An array with the shape of the given array, but the data type and order of the data are not initialized (random).

>>> import numpy as np
>>> np.empty([2, 2)]
array([[1, 0.],
       [0., 1.]])
>>> np.empty([2, 2], dtype=int)
array([[4607182418800017408, 0],
       [ 0, 4607182418800017408])
>>>
Note:Note - The array elements are random values because they are not initialized.

numpy.empty_like

numpy.empty returns a new array with the same shape and type as the given array.

numpy.empty_like(prototype, dtype=None, order='K', subok=True, shape=None)

Return a new array with the same shape and type as the given array

Parameter

prototype - The shape and data type of the source array define these same properties of the returned array.dtype - Overwrite the data type of the result.order - Overwrite the memory layout of the result. If prototypeFortran is continuous, 'A' represents 'F', otherwise 'C'.'K' indicates that the layout of the prototype is matched as much as possible.subok - If True, the newly created array will use the subclass type of 'a', otherwise it will be the base class array. The default is True.shape - Overwrite the shape of the result. If order='K' and the number of dimensions remains unchanged, the order will be maintained; otherwise, it implies order='C'.

Return value: A new array with the same shape and type as the given array.

>>> import numpy as np
>>> a = (1,2,3], [4,5,6]]) # a is array-like
>>> np.empty_like(a)
array([[ 6917529027641081856, -6917520256071729910, 98],
       [ 0, 0, 0]]
>>> a = np.array([[1, 2, 3.],[4,5,6.]])
>>> np.empty_like(a)
array([[ 2.68156159e+154, 2.68156159e+154, 3.32479618e+181],
       [ 1.78476163e+185, -1.73059781e-077, 4.21535080e-309])

numpy.zeros

Create an array of specified size, filled with 0s:

numpy.zeros(shape, dtype=float, order='C')

Parameter

shape - The shape of the empty array.dtype - The output data type required by the array, such as numpy.int8。Default value is numpy.float64.order - '{'C', 'F'},optional, default: 'C',indicating that data is stored in memory in row (C) or column (Fortran) style.

Return value: A zero array with the shape, data type, and order of the given array.

>>> import numpy as np
>>> np.zeros(5)
array([0., 0., 0., 0., 0.])
>>> np.zeros(5,), dtype=int)
array([0, 0, 0, 0, 0])
>>> np.zeros(2, 1))
array([[0.],
       [0.]])
>>> s = (2,2)
>>> np.zeros(2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype
array([(0, 0), (0, 0)], dtype=[('x', '<i)4' ),="" ('y',="" '

numpy.zeros_like

zeros_like returns a zero array with the same shape and type as the given array.

numpy.zeros_like(a, dtype=None, order='K', subok=True, shape=None)[source]

Parameter

a - An attribute that limits the array shape and data type returned.dtype - The output data type required by the array.order - Override the memory layout of the result.subok - If True, the newly created array will use the subclass type of 'a', otherwise it will be the base class array. The default is True.shapeint - Override the shape of the result.

Return value: an array of zeros with the same shape and type.

>>> import numpy as np
>>> x = np.arange(6)
>>> x = x.reshape((2, 3))
>>> print(x)
[[0 1 2]
 [3 4 5]]
>>> np.zeros_like(x)
array([[0, 0, 0],
       [0, 0, 0]]
>>> y = np.arange(3, dtype=float)
>>> y
array([0., 1, 2.])
>>> np.zeros_like(y)
array([0., 0., 0.])

numpy.ones

Create an array of specified shape, with array elements filled with 1 to fill:

numpy.ones(shape, dtype=None, order='C')

Parameter

shape - Array shape.dtype - Data type, optionalorder - 'C' for row arrays in C, or 'F' for column arrays in FORTRAN

>>> import numpy as np
>>> np.ones(5)
array([)1, 1, 1, 1, 1.])
>>> np.ones(5,), dtype=int)
array([)1, 1, 1, 1, 1)]
>>> np.ones(2, 1))
array([[1.],
       [1.]])
>>> s = (2,2)
>>> np.ones(s)
array([[1, 1.],
       [1, 1.]])

numpy.ones_like

zeros_like returns an array with the same shape and type as the given array.

numpy.ones_like(a, dtype=None, order='K', subok=True, shape=None)

Parameter

a - An attribute that limits the array shape and data type returned.dtype - The output data type required by the array.order - Override the memory layout of the result.subok - If True, the newly created array will use the subclass type of 'a', otherwise it will be the base class array. The default is True.shape - Override the shape of the result.

Return value: an array of zeros with the same shape and type.

>>> import numpy as np
>>> x = np.arange(6)
>>> x = x.reshape((2, 3))
>>> x
array([[0, 1, 2],
       [3, 4, 5])
>>> np.ones_like(x)
array([[1, 1, 1],
       [1, 1, 1])
>>> y = np.arange(3, dtype=float)
>>> y
array([0., 1, 2.])
>>> np.ones_like(y)
array([)1, 1, 1.])

numpy.arange

numpy.arange([start,] stop, [step,] dtype = None)

Return the values at uniform intervals within the given interval.
Generate values within the half-open interval (i.e., including start but not including stop). For integer parameters, this function is equivalent to Python's built-in range function, but returns an ndarray instead of a list. [start, stop)

Parameter

start - The beginning of the interval. The interval includes the value. The default starting value is 0.stop - The interval ends. This interval does not include the value unless in some cases, step is not an integer, and floating-point rounding affects the length of out.step - The spacing between values. For any output, this is the distance between two adjacent values. The default step size is1.dtype - The type of the output array.

Return value: an array of evenly spaced values.

>>> import numpy as np
>>> np.arange(3)
array([0., 1, 2)]
>>> np.arange(3.0)
array([0., 1, 2.])
>>> np.arange(3,7)
array([)3, 4, 5, 6)]
>>> np.arange(3,7,2)
array([)3, 5)]

numpy.linspace

The numpy.linspace function is used to create a one-dimensional array, which is an arithmetic sequence, in the following format:

np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

Parameter

start - The starting value of the sequence.stop - The terminal value of the sequence. If endpoint is true, this value is included in the sequence.num - The number of samples to be generated with equal step size, default is50.endpoint - If this value is true, the series contains the stop value, otherwise it does not, the default is True.retstep - If True, the spacing will be displayed in the generated array, otherwise not.dtype - The data type of ndarray.

The following example uses three parameters, setting the starting point to 1 The terminal point is 10The number of series is 10.

>>> import numpy as np
>>> a = np.linspace(1,10,10)
>>> print(a)
[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10]
>>> a = np.linspace(10, 20, 5, endpoint=False)
>>> print(a)
[10. 12. 14. 16. 18]
>>> a = np.linspace(1,10,10, retstep=True)
>>> print(a)
(array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10).reshape([ 1.0)
>>> b = np.linspace(1,10,10).reshape([10,1)]
>>> print(b)
[[ 1]
 [ 2]
 [ 3]
 [ 4]
 [ 5]
 [ 6]
 [ 7]
 [ 8]
 [ 9]
 [10.]]

numpy.asarray

Convert Python's basic data types (such as lists, tuples, etc.) directly to ndarray:

>>> import numpy as np
>>> ls1 = [10, 42, 0, -17, 30]
>>> nd1 =np.array(ls1)
>>> print(nd1)
[ 10 42 0 -17 30]
>>>
>>> print(type(nd1))

numpy.asarraySimilar numpy.array, but the numpy.asarray parameter has only three, two less than numpy.array.

numpy.asarray(a, dtype=None, order=None)

Parameter

a - Any form of input parameter, which can be a list, a tuple of a list, a tuple, a tuple of a tuple, a list of tuples, or a multidimensional array.dtype - Data type, optional.order - The number of samples to be generated with equal step size, default is50.endpoint - Optional, with two options 'C' and 'F', respectively representing row-major and column-major order, the storage order of elements in computer memory.

>>> import numpy as np
>>> x = [1,2,3]
>>> a = np.asarray(x)
>>> a
array([)1, 2, 3)]
>>> x = (1,2,3)
>>> a = np.asarray(x)
>>> print(a)
[1 2 3]
>>> x = [(1,2,3),(4,5)]
>>> a = np.asarray(x)
>>> print(a)
[(1, 2, 3) (4, 5)]
>>> x = [1,2,3]
>>> a = np.asarray(x, dtype=float)
>>> print(a)
[1. 2. 3]

numpy.frombuffer

numpy.frombuffer is used to implement dynamic arrays.
The numpy.frombuffer method accepts buffer input parameters and reads in as a stream to convert to ndarray objects.

numpy.frombuffer(buffer, dtype=float, count= -1, offset = 0)
Note:When buffer is a string, Python3 By default, str is a Unicode type, so it needs to be converted to bytestring by adding b in front of the original str.

Parameter

buffer - Can be any object, which will be read in as a stream.dtype - Returns the data type of the array, optionalcount - The number of data read, default is-1Read all data.offset - The starting position of the read, default is 0.

>>> import numpy as np
>>> s = b'Hello w3codebox'
>>> a = np.frombuffer(s, dtype='S1)
>>> print(a)
[b'H' b'e' b'l' b'l' b'o' b' ' b'L' b'i' b'd' b'i' b'h' b'u' b'o']

numpy.fromiter

The numpy.fromiter method establishes an ndarray object from an iterable, returning a one-dimensional array.

numpy.fromiter(iterable, dtype, count=-1)

Parameter

iterable - Iterablesdtype - Returns the data type of the arraycount - The number of data read, default is-1Read all data.

>>> import numpy as np
>>> # Use the range function to create a list object
>>> list=range(5)
>>> it=iter(list)
>>> x=np.fromiter(it, dtype=float)
>>> print(x)
[0. 1. 2. 3. 4]

Generating an array using the random module

In order to train the model more effectively and improve the performance of the model, certain conditions need to be met for some initializations, such as normal distribution or uniform distribution, etc. Several commonly used methods in the np.random module are introduced as shown in the table below.

FunctionDescription
np.random.randomGenerate Random Numbers Between1Between Random Numbers
np.random.uniformGenerate Uniform Distribution Random Numbers
np.random.randnGenerate Standard Normal Random Numbers
np.random.randintGenerate Random Integers
np.random.normalGenerate Normal Distribution
np.random.shuffleRandomly Shuffle Order
np.random.seedSet Random Number Seed
random_sampleGenerate Random Floating Point Numbers
>>> import numpy as np
>>> # Generate all 0 of 3x3 Matrix
>>> nd5 =np.zeros([3, 3)]
>>> print("nd5 =\n", nd5)
nd5 =
 [[0. 0. 0.]]
 [0. 0. 0.]
 [0. 0. 0.]]
>>> # Generate all 1 of 3x3 Matrix
>>> nd6 = np.ones([3, 3)]
>>> print("nd6 =\n", nd6)
nd6 =
 [[1. 1. 1]
 [1. 1. 1]
 [1. 1. 1.]]
>>>
>>> # Generate 4 Order Unit Matrix
>>> nd7 = np.eye(4)
>>> print("nd7 =\n", nd7)
nd7 =
 [[1. 0. 0. 0.]
 [0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [0. 0. 0. 1.]]
>>> # Generate 4 Order Diagonal Matrix
>>> nd8 = np.diag([1, 8, 3, 10)]
>>> print("nd8 =\n", nd8)
nd8 =
 [[ 1 0 0 0]
 [ 0 8 0 0]
 [ 0 0 3 0]
 [ 0 0 0 10]]