AppDividend
Latest Code Tutorials

Numpy Arange: How to Use np.arange() Function

0

Numpy arange() is one of the array creation functions based on numerical ranges. It creates the instance of ndarray with evenly spaced values and returns the reference to it.

Creating NumPy arrays is essentials when you’re working with other Python libraries that rely on them, like SciPy, Pandas, scikit-learn, Matplotlib, and more. NumPy is a perfect library for creating and working with arrays because it enables performance boosts, allows you to write concise code, and offers useful routines.

Numpy has its most important of array called ndarray. NumPy offers a lot of array creation routines for different circumstances. The arange() is one such function based on numerical ranges. It’s often referred to as np.arange because np is a widely used abbreviation for NumPy.

Numpy arange()

The Numpy arange() method returns the ndarray object containing evenly spaced values within the given range.  The np.arange() function returns an evenly spaced values within a given interval.

For integer arguments, the method is equivalent to a Python inbuilt range function but returns the ndarray rather than a list.

Syntax

The syntax of numpy.arange() function is the following.

numpy.arange(start, stop, step, dtype)

Parameters

The parameters are the following.

start: number, optional. Start of an interval. The interval includes this value. The default start value is 0.

stop: number. End of the interval. The interval does not contain stop value, except in some cases where a step is not an integer and floating-point round-off affects the length of out

step: number, optional. step can’t be zero. Otherwise, you’ll get a ZeroDivisionError. You can’t move away anywhere from the start if the increment or decrement is 0.

dtype: The type of an output array. If the dtype is not given, infer the data type from the other input arguments. If dtype is omitted, arange() will try to deduce the type of the array elements from the types of start, stop, and step.

Return Value

It returns an array. You can find more details on the parameters and the return value of arange() function in the official documentation.

Example of np arange

Let’s see the NumPy arange function example in Jupyter Notebook.

When working with NumPy routines, you have to import Numpy first.

Write the following code inside the first cell.

import numpy as np

Now, you have NumPy imported, and you’re ready to apply arange().

Run that cell using Ctrl + Enter and then write the following code in the next cell.

npdata = np.arange(3)
npdata

See the output below.

NumPy Arange Tutorial

It has created a numpy array from 0 to 2 elements with a length of 3.

Let’s see another example. Write the following Python code in the cell.

npdata = np.arange(40)
npdata.shape = (5, 8)
npdata

In the above code, we have defined an array with the items of 40, and then we have numpy array’s shape attribute to shape that array into 5 rows and 8 columns. See the output.

Python NumPy Functions

Start and stop parameters set in numpy arange

Let’s define the start and stop parameters in the numpy arange function. See the output.

npdata = np.arange(1,21,3)
npdata

In the above code, we have passed the first parameter as a starting point, then go to 21 and with step 3. See the output below.

Start and stop parameters set in Python NumPy

The above code sample returns an array with the array starting from 1 and up to 21 with the step of 3. So 1, (1 +3 = 4), (4 + 3 = 7),… up to 21 as an endpoint.

Now, let’s see another example.

#app.py

import numpy as np

print(np.arange(1, 21.1, 3))

See the output.

➜  pyt python3 app.py
[ 1.  4.  7. 10. 13. 16. 19.]
➜  pyt

In this case, you get the array with seven elements.

Notice that this example creates an array of floating-point numbers, unlike the previous one. That’s because you haven’t defined dtype and arange() deduced it for you.

Providing all positional range arguments

In the np arange function, we can provide all three arguments at once and seek the desired output.

import numpy as np

data = np.arange(start=2, stop=12, step=3)
print(data)

Output

[2  5  8 11]

In this example, the start is 2. Therefore, the first item of the obtained array is 2. The step is 3, which is why your second value is 2+3, which is 5, while the third value in an array is 5+3, which equals 8 and final value 8 + 3 = 11.

Now, You can pass start, stop, and step as positional arguments as well.

import numpy as np

data = np.arange(2, 12, 3)
print(data)

Output

[ 2  5  8 11]

The above code sample is equivalent to but more concise than the previous one.

Providing float arguments

If we provide the float arguments, then the output array values will be floats. If we pass steps in float, then it will calculate as it but returns the array float values.

import numpy as np

data = np.arange(2, 11.1, 3)
print(data)

Output

[ 2.  5.  8. 11.]

In this case, you get the array with four elements that include 11.

Notice that this example creates an array of floating-point numbers, unlike the previous one. That’s because you haven’t defined dtype and arange() deduced it for you.

Providing Two Range Arguments

You can omit the step parameter. In the following case, arange() uses its default value of 1. The following two statements are equivalent.

import numpy as np

data = np.arange(2, 5)
print(data)

Output

[2 3 4]

Using the np.arange() method with increment 1 is a widespread case in practice. Again, you can write a previous example more precisely with the positional arguments start and stop.

Providing One Range Argument

The numpy arange() function at least takes one argument to work correctly. To be more concise, you have to provide a start. But what happens if you omit to stop? How does np.arange() know when to stop counting?

In this case, an array starts at 0 and ends before the value of the start is reached! Again, the default value of the step is 1. In other words, arange() assumes that you have provided stop (instead of start), and that start is 0, and step is 1.

import numpy as np

data = np.arange(5)
print(data)

Output

[0 1 2 3 4]

This is the most Pythonic way to create NumPy array that starts at 0 and has an increment of 1. A single argument indicates where the counting stops. The final output array starts at 0 and has an increment of 1.

TypeError in arange()

If you try to provide a stop without start explicitly, then you’ll get a TypeError.

import numpy as np

data = np.arange(stop = 5)
print(data)

Output

Traceback (most recent call last):
  File "app.py", line 3, in <module>
    data = np.arange(stop = 5)
TypeError: arange() missing required argument 'start' (pos 1)

You got the TypeError because arange() doesn’t allow you to avoid the first argument that corresponds to start explicitly. If you provide the single argument, then it has to start, but arange() will use it to define where the counting stops. If you explicitly provide stop without start, then you will get this error saying TypeError: arange() missing required argument ‘start’ (pos 1).

Passing negative arguments

If you provide negative values for the start or both start and stop, and have a positive step, then arange() will work the same way as with all positive arguments:

# app.py

import numpy as np

print(np.arange(-8, -2, 2))

See the output.

➜  pyt python3 app.py
[-8 -6 -4]
➜  pyt

The counting begins with the value of start, repeatedly incrementing by step, and ending before a stop is reached.

Sometimes you’ll want an array with the values decrementing from left to right. In such cases, you can use arange() with a negative value for step, and with a start greater than stop.

Counting Backwards

Sometimes you will want an array with the values decrementing from left to right. In such cases, you can use arange() with a negative value for step, and with a start greater than stop.

import numpy as np

data = np.arange(4, 1, -2)
print(data)

Output

[4 2]

In the above code, the start is 4, and the resulting array begins with this value. The step is -2, so the second value is 4+(−2), which is 2. Now, counting stops here since stop (0) is reached before the next value (-2). So, we get [4, 2] in the output.

In these scenarios, the start is greater than stop, and it is negative, and you’re counting backward.

Working with empty arrays

There are several edge cases where you can obtain empty NumPy arrays with arange(). These are regular instances of numpy—ndarray without any elements.

If you provide equal values for a start and stop, then you’ll get an empty array.

#app.py

import numpy as np

print(np.arange(11, 11))

See the output.

➜  pyt python3 app.py
[]
➜  pyt

Numpy arange reshape() function

numpy.reshape(array, shape, order = ‘C’)

It shapes an array without changing the data of array.

#app.py

import numpy as np 
  
arr = np.arange(8) 
print("Original Array : \n", arr) 
  
# shape arr with 2 rows and 4 columns 
arr = np.arange(8).reshape(2, 4) 
print("\nArray reshaped with 2 rows and 4 columns : \n", arr) 
  
# shape arr with 2 rows and 4 columns 
arr = np.arange(8).reshape(4 ,2) 
print("\nArray reshaped with 2 rows and 4 columns : \n", arr) 
  
# Constructs 3D arr 
arr = np.arange(8).reshape(2, 2, 2) 
print("\nOriginal Array reshaped to 3D : \n", arr)

See the output.

➜  pyt python3 app.py
Original Array :
 [0 1 2 3 4 5 6 7]

Array reshaped with 2 rows and 4 columns :
 [[0 1 2 3]
 [4 5 6 7]]

Array reshaped with 2 rows and 4 columns :
 [[0 1]
 [2 3]
 [4 5]
 [6 7]]

Original Array reshaped to 3D :
 [[[0 1]
  [2 3]]

 [[4 5]
  [6 7]]]
➜  pyt

Numpy Datatypes

  1. All items in the NumPy array are of the same type, called dtype (data type).
  2. Numpy dtypes allow for more triturate than Python’s inbuilt numeric types.
  3. Some Numpy routines can accept Python numeric types and vice versa.
  4. Some Numpy dtypes have platform-dependent definitions.
  5. In few cases, Numpy dtypes have aliases that coincide to the names of Python inbuilt types.

See the following code.

import numpy as np

data = np.arange(4, 1, -2)
print(data.dtype)

Output

int64

The arange() function will try to deduce the dtype of the resulting array. It depends on the types of start, stop, and step.

Here, the array created by np arange() function is [4, 2]. That’s why the dtype of the array data will be one of the integer types served by Numpy.

In this case, Numpy chooses an int64 dtype by default. This is a 64-bit (8-bytes) integer type.

The parameter dtype=int doesn’t refer to Python int. It translates to NumPy int64 or simply np.int. So, in the output, we got int64, which is not the same as Python int. It is a 64-bit integer type.

Define Data type while creating an array

We can define a data type bypassing a dtype parameter as int, float, or whatever allowed data type while creating a new array using arange() function. If we pass the float data type, then output values will be the float.

import numpy as np

data = np.arange(5, dtype=float)
print(data)
print(data.dtype)

Output

[0. 1. 2. 3. 4.]
float64

In the output, you can see that the arange() function has generated float-pointed values instead of regular integers.

The argument dtype=float doesn’t refer to Python float. It translates to NumPy float64 or simply np.float. So, in the output, we got float64, which is not the same as Python float. It is a 64-bit float type.

Numpy provides us several integer fixed-sized dtypes that differ in memory and limits:

  1. np.int8: It is a 8-bit signed integer (from -128 to 127)
  2. np.uint8: It is a 8-bit unsigned integer (from 0 to 255)
  3. np.int16: It is a 16-bit signed integer (from -32768 to 32767)
  4. np.uint16: It is a 16-bit unsigned integer (from 0 to 65535)
  5. np.int32: It is a 32-bit signed integer (from -2**31 to 2**31-1)
  6. np.uint32: It is a 32-bit unsigned integer (from 0 to 2**32-1)
  7. np.int64: It is a 64-bit signed integer (from -2**63 to 2**63-1)
  8. np.uint64: It is a 64-bit unsigned integer (from 0 to 2**64-1)

If you need other integer types for the items of your array, then you just need to specify the dtype.

import numpy as np

data = np.arange(5, dtype=np.float32)
print('The data:', data)
print('The data type: ', data.dtype)
print('The size in bytes: ', data.itemsize)

Output

The data: [0. 1. 2. 3. 4.]
The data type:  float32
The size in bytes:  4

Numpy arange vs. Python range

For large arrays, np.arange() should be the faster solution.

The range() gives you a regular list (python 2) or a specialized “range object” (like a generator; python 3), np.arangegives you a numpy array. If you care about speed enough to use numpy, use numpy arrays.

NumPy’s arrays are more compact than Python lists: a list of lists as you describe, in Python, would take at least 20 MB or so, while a NumPy 3D array with single-precision floats in the cells would fit in 4 MB. Access to reading and writing items is also faster with NumPy.

NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented.

Finally, Numpy arange Example is over.

See also

How To Create NumPy Arrays

Python Pandas DataFrame

Pandas DataFrame read_csv()

Python Pandas Series

Python property()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.