- 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.
Here is the general form:
np.arrange(start, stop=None, step=1, dtype=None)
start: The first value in the sequence.
stop: The limiting value: the last element of the sequence will never be greater than or equal to this value.
>>> print np.arrange(1.0, 4.0) [ 1. 2. 3.]
If you omit the stop value, you will get a sequence starting at zero and using start as the limiting value.
>>> print np.arrange(4) [0 1 2 3]
step: The common difference between successive values of the array. The default value is one.
>>>np.arrange(0, 1, 0.2) [ 0. , 0.2, 0.4, 0.6, 0.8]
dtype: Use this argument to force representation using a specific type.
>>> print np.arrange(10) [0 1 2 3 4 5 6 7 8 9] >>> print np.arrange(10, dtype=np.float_) [ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
Related Downloads
Data Science in Finance: 9-Book Bundle
Master R and Python for financial data science with our comprehensive bundle of 9 ebooks.
What's Included:
- Getting Started with R
- R Programming for Data Science
- Data Visualization with R
- Financial Time Series Analysis with R
- Quantitative Trading Strategies with R
- Derivatives with R
- Credit Risk Modelling With R
- Python for Data Science
- Machine Learning in Finance using Python
Each book includes PDFs, explanations, instructions, data files, and R code for all examples.
Get the Bundle for $29 (Regular $57)Free Guides - Getting Started with R and Python
Enter your name and email address below and we will email you the guides for R programming and Python.