A quick overview of different ways of creating NumPy arrays
Numpy- Numerical Python
Numpy is multidimensional array library used for scientific computing.
Why use numpy:
Numpy is faster,convenient and takes less memory.
Numpy is homogeneous. Items in the array are of same data type.
Install numpy library:
pip install numpy
Import numpy library
import numpy as np
How to create numpy array:
- array() — creates array from list/tuple
One dimensional arrays:
A frequent error consists in calling
array with multiple arguments, rather than providing a single sequence as an argument.
Two dimensional arrays:
array transforms sequences of sequences into two-dimensional arrays, sequences of sequences of sequences into three-dimensional arrays, and so on.
Type of the array can be explicitly specified during creation.
arange function is used to create sequence of numbers similar to Python built-in range function,but returns an array.
One dimensional array:
arange()-accepts floating-point arguments also.
Creating an array of float numbers.
Creating an array of complex numbers
Often, the elements of an array are originally unknown, but its size is known. Hence, NumPy offers several functions to create arrays with initial placeholder content. These minimize the necessity of growing arrays, an expensive operation.
zeros() ones() empty()
Creates an array full of zeros.
Return an array of zeros with the same shape and type as a given array.
Creates an array full of ones
Return an array of ones with the same shape and type as a given array.
empty creates an array whose initial content is random and depends on the state of the memory. By default, the dtype of the created array is
creates an array filled with the given value.
Return a full array with the same shape and type as a given array.
creates an array filled with evenly spaces samples
Returns 6 evenly spaced samples, calculated over the interval 1,10.
retstep-returns the step.
The endpoint is excluded:
Returns array filled with zeros except the kth diagonal, whose values are equal to 1.
k=-1 means the lower part of the diagonal will be one
k=1 means the upper part of the diagonal will be one.
Returns square array with ones on the main diagonal.
creates an array of given shape 5 with random samples between 0 and 1
creates an array of shape(2,2) with random samples from 1 to 5
- The function
zeroscreates an array full of zeros, the function
onescreates an array full of ones, and the function
emptycreates an array whose initial content is random and depends on the state of the memory. By default, the dtype of the created array is
- Difference between range() and arange()