Skip to content

2D array in Python NumPy

  • by

In Python NumPy, a 2D array is a multi-dimensional array that contains elements arranged in rows and columns. It is represented by the ndarray object, which is provided by the NumPy library.

In Python, you can create a 2D array using the NumPy library. Here’s the syntax:

import numpy as np

# Create a 2D array
my_array = np.array([[element11, element12, element13],
                     [element21, element22, element23],
                     [element31, element32, element33]])

In this syntax, elementij represents the element at the ith row and jth column of the array.

Here’s an example that demonstrates the syntax:

import numpy as np

# Create a 2D array
my_array = np.array([[1, 2, 3],
                     [4, 5, 6],
                     [7, 8, 9]])

You can also specify the data type of the elements using the dtype parameter. For example, to create a 2D array with floating-point numbers, you can use the following syntax:

my_array = np.array([[1.0, 2.0, 3.0],
                     [4.0, 5.0, 6.0],
                     [7.0, 8.0, 9.0]], dtype=float)

In this case, we specified the dtype as float, so the array elements will be floating-point numbers.

Once you have created a 2D array, you can perform various operations on it using the functions and methods provided by NumPy.

2D array in Python NumPy example

Simple example code.

import numpy as np

# Create a 2D array
my_array = np.array([[1, 2, 3],
                     [4, 5, 6],
                     [7, 8, 9]])

# Accessing elements
print(my_array[0, 0])  # Output: 1
print(my_array[1, 2])  # Output: 6

# Slicing rows and columns
print(my_array[0])     # Output: [1 2 3]
print(my_array[:, 1])  # Output: [2 5 8]

# Array shape
print(my_array.shape)  # Output: (3, 3)

# Array manipulation
my_array_transposed = np.transpose(my_array)
print(my_array_transposed)


# Mathematical operations
my_array_squared = my_array ** 2
print(my_array_squared)

# Sum of rows and columns
row_sum = np.sum(my_array, axis=1)
print('Row',row_sum)  # Output: [ 6 15 24]

column_sum = np.sum(my_array, axis=0)
print('Column', column_sum)  # Output: [12 15 18]

Output:

2D array in Python NumPy

Comment if you have any doubts or suggestions on this Python Array topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading