Lessons
- Python Dictionaries
- Comparison Operators in Python
- Logical Operators in Python
- Conditional Statements in Python
- For Loop in Python
- While Loop in Python
- How to loop over python dictionaries and Numpy arrays
- What is NumPy in Python
- ndarray - Methods and Data Type
- NumPy - Methods to Create Arrays
- Python NumPy - Numerical Operations on Arrays
- Python NumPy - Indexing and Slicing Arrays
NumPy - Methods to Create Arrays
We learned about how to create an array using np.array()
. NumPy also provides a few other methods to create new arrays.
Functions np.zeros() and np.ones()
The functions zeros and ones create new arrays of specified dimensions filled with these values (Os and 1s). These are perhaps the most commonly used functions to create new arrays:
>>> import numpy as np
>>> np.zeros(6)
array([ 0., 0., 0., 0., 0., 0.])
>>> np.zeros([2,3])
array([[ 0., 0., 0.],
[ 0., 0., 0.]])
>>> np.ones([3,3])
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
>>>
Function zeros_like() and ones_like()
The zeros_like()
and ones_like()
functions create a new array with the same dimensions and type of an existing one:
>>> a = np.array([[1, 2, 3], [4, 5, 6]], float)
>>> np.zeros_like(a)
array([[ 0., 0., 0.],
[ 0., 0., 0.]])
>>> np.ones_like(a)
array([[ 1., 1., 1.],
[ 1., 1., 1.]])
>>>
Function np.arrange()
The arrange
function is similar to the range
function but returns an array. It returns evenly spaced values within a given interval.
This content is for paid members only.
Join our membership for lifelong unlimited access to all our data science learning content and resources.