Add dimension to array python

Add Dimension to NumPy Array

Add Dimension to NumPy Array

  1. Add Dimension to NumPy Array With the numpy.expand_dims() Function
  2. Add Dimension to NumPy Array With the numpy.newaxis Function in Python

This tutorial will introduce the methods to add a new dimension to a NumPy array in Python.

Add Dimension to NumPy Array With the numpy.expand_dims() Function

The numpy.expand_dims() function adds a new dimension to a NumPy array. It takes the array to be expanded and the new axis as arguments and returns a new array with extra dimensions. We can specify the axis to be expanded inside the axis parameter of the numpy.expand_dims() function. See the following code example.

import numpy as np  array = np.array([1,2,3]) print(array.shape)  array = np.expand_dims(array, axis = 0) print(array.shape)  array = np.append(array, [[4,5,6]], axis=0) print(array) 

In the above code, we first created a 1D array array with the np.array() function and printed the shape of the array with the array.shape property. We then converted the array to a 2D array with the np.expand_dims(array, axis=0) function and printed the new shape of the array with the array.shape property. In the end, we appended new elements to the array with the np.append() function and printed the elements of the array .

Add Dimension to NumPy Array With the numpy.newaxis Function in Python

The previous approach does the job and works fine for now. The only problem is that the previous method has been deprecated and will probably not work with Python’s newer versions in the future. The numpy.newaxis method can also be used to achieve the same goal as the previous method but with even lesser code and complexity. With this method, we also don’t have to worry about not being supported in Python’s later versions. The numpy.newaxis method adds a new dimension to our array in Python.

import numpy as np  array = np.array([1,2,3]) print(array.shape)  array = array[np.newaxis] print(array.shape)  array = np.append(array, [[4,5,6]], axis=0) print(array) 

We converted the array to a 2D array with the array[np.newaxis] method and printed the new shape of the array with the array.shape property. In the end, we appended new elements to the array with the np.append() function and printed the elements of the array .

Читайте также:  Getting Started: Serving Web Content

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

Источник

Different Ways to Add Dimension to NumPy Array

add dimension to numpy array

This article will discuss the various ways we can add and change dimensions to the NumPy array. A NumPy array consists of values of the same type. A tuple of positive integers or “index values” is used to access the elements. The number of dimensions is the rank of the array. A similar sequential data type in Python in Lists. A list in Python is resizeable and can contain elements of different types.

NumPy arrays are effective in the following ways:

  • NumPy arrays take up lesser space
  • They have better performance than Python lists
  • NumPy arrays have optimized functionality (ex: Arithmetic Operations)

Let’s look at various methods to manipulate array dimensions.

Add a Dimension to NumPy Array

Using numpy.expand_dims()

The numpy.expand_dims() function adds a new dimension to a NumPy array. It takes the array to be expanded and the new axis as arguments. It returns a new array with extra dimensions. We can specify the axis to be expanded in the axis parameter.

Example 1

import numpy as np myArray = np.array([2,4,6]) print(myArray.shape) myArray = np.expand_dims(myArray, axis = 0) print(myArray.shape) myArray = np.append(myArray, [[8,10,12]], axis=0) print(myArray)

Example 2

import numpy as np myArray = np.array(["Python","Java","Cpp"]) print(myArray.shape) myArray = np.expand_dims(myArray, axis = 0) print(myArray.shape) myArray = np.append(myArray, [["R","Go","Kotlin"]], axis=0) print(myArray)

Outputs/Explanation

(3,) (1, 3) [['Python' 'Java' 'Cpp'] ['R' 'Go' 'Kotlin']]

In the above code, we first created a 1D array myArray with the np.array() function and printed the shape of myArray with the array.shape property. We then converted the array to a 2D array with the np.expand_dims(myArray, axis=0) function and printed the new shape. Finally, we appended the new elements into the array and printed it.

Читайте также:  Css style display true

Add a Dimension Using numpy.newaxis()

The numpy.newaxis method can also be used to achieve the same. It has lesser code and complexity compared to the previous example.

Example 1

import numpy as np myArray = np.array([3,6,9]) print(myArray.shape) myArray = myArray[np.newaxis] print(myArray.shape) myArray = np.append(myArray, [[12,15,18]], axis=0) print(myArray)

Example 2

import numpy as np myArray = np.array(["Google","Microsoft","Apple"]) print(myArray.shape) myArray = myArray[np.newaxis] print(myArray.shape) myArray = np.append(myArray, [["Riot","Ubisoft","Uber"]], axis=0) print(myArray)

Outputs/Explanation

(3,) (1, 3) [['Google' 'Microsoft' 'Apple'] ['Riot' 'Ubisoft' 'Uber']]

We converted the array to a 2D array using myArray[np.newaxis] method and printed the new shape of the array with the array.shape property. Finally, we appended new elements to the array with the np.append() function and printed the elements of the array .

Add Dimensions to an Image Array

It is possible to add dimensions to an image array as well. The default method is to use .newaxis()

import numpy as np myImage = image[imagedata, np.newaxis]

Alternatively, we can use .expand_dims()

myImage = np.expand_dims("image.jpg", )

Changing the Dimensions of NumPy Arrays

Using .shape()

Using .shape() we can change the dimensions (shape) of the NumPy array. This is the most straightforward method. Let’s take a look at the following program.

Example 1

import numpy as np myArray = np.array([1,3,5,7]) print(myArray) print("initial shape of the array") print(myArray.shape) print("after changing the shape") myArray.shape = (2,2) print(myArray)

Example 2

import numpy as np myArray = np.array(["red","green","blue","violet"]) print(myArray) print("initial shape of the array") print(myArray.shape) print("after changing the shape") myArray.shape = (2,2) print(myArray)

Outputs/Explanation

[1 3 5 7] initial shape of the array (4,) after changing the shape [[1 3] [5 7]]
['red' 'green' 'blue' 'violet'] initial shape of the array (4,) after changing the shape [['red' 'green'] ['blue' 'violet']]

Initially, we create an array myArray of 4 elements. The initial shape of the array is (4,0). After passing .shape() as (2,2), the shape of the array is changed accordingly.

Читайте также:  Java regexp именованные группы

Using .reshape()

The reshape function takes a parameter order . This allows us to reshape either row or column-wise.

Example 1

import numpy as np myArray = np.arange(1,10) print(myArray) print("converted into a 3x3: ") print(np.reshape(myArray, (3,3)))

Example 2

import numpy as np myArray = np.arange(1,26) print(myArray) print("converted into a 5x5: ") print(np.reshape(myArray, (5,5)))

Outputs/Explanation

[1 2 3 4 5 6 7 8 9] converted into a 3x3: [[1 2 3] [4 5 6] [7 8 9]]
[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25] converted into a 5x5: [[ 1 2 3 4 5] [ 6 7 8 9 10] [11 12 13 14 15] [16 17 18 19 20] [21 22 23 24 25]]

Initially, we create an array myArray of 9 elements using arange . The shape of the array is changed using .reshape() , which converts into a 3×3 array. The second example demonstrates the same, with a 5×5 array.

How to Create a 2D Array in Python

Let’s see how we can create a 2D array in Python using np.array() .

Function Syntax for np.array()

numpy.array ( object, dtype=None, copy=True, order='K', subok=False, ndim=0, like=None )
import numpy as np myArray2D = np.array([[23,4],[20,20]]) print(myArray2D)

Output/Explanation

In the above code first, we have imported a numpy library and then created a variable myArray2D and assign a numpy array function for creating a 2D array.

FAQs

With the help of the .expand_dims() function under the NumPy module, we can add multiple dimensions to your array. However, the values must be added separately

Conclusion

In this article, we have discussed how we can add or change the dimensions of a NumPy array. We have also discussed how .expand_dims() allows you to add multiple dimensions to an array.

Источник

Оцените статью