Different Ways to 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.

Contents

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

Example 1

```(3,)
(1, 3)
[[ 2  4  6]
[ 8 10 12]]```

Example 2

```(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.

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

print(myArray.shape)

myArray = myArray[np.newaxis]
print(myArray.shape)

myArray = np.append(myArray, [["Riot","Ubisoft","Uber"]], axis=0)
print(myArray)
```

Outputs/Explanation

Example 1

```(3,)
(1, 3)
[[ 3  6  9]
[12 15 18]]```

Example 2

```(3,)
(1, 3)
['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", <required dimension>)
```

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

Example 1

```[1 3 5 7]
initial shape of the array
(4,)
after changing the shape
[[1 3]
[5 7]]```

Example 2

```['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.

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

Example 1

```[1 2 3 4 5 6 7 8 9]
converted into a 3x3:
[[1 2 3]
[4 5 6]
[7 8 9]]```

Example 2

```[ 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

```[[23  4]
[20 20]]```

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

How do I add a Second or Third Dimension to the NumPy array?

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.

Subscribe
Notify of