NumPy Lesson 4 – Array Attributes | Dataplexa

NumPy Array Attributes

In the previous lesson, you learned how to create NumPy arrays using different methods. Now, it is important to understand the properties of these arrays.

NumPy provides built-in attributes that describe the structure, size, and data type of an array. These attributes help you understand and debug your data.


Why Array Attributes Matter

Array attributes tell you:

  • How many elements an array contains
  • How the data is shaped (rows and columns)
  • What type of data is stored inside the array

These are essential when working with real-world datasets and numerical models.


The ndim Attribute

The ndim attribute tells you how many dimensions an array has.

import numpy as np

arr = np.array([10, 20, 30])
print(arr.ndim)

Output:

1

This means the array is one-dimensional.


The shape Attribute

The shape attribute returns a tuple representing the size of each dimension.

matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix.shape)

Output:

(2, 3)

This means the array has 2 rows and 3 columns.


The size Attribute

The size attribute returns the total number of elements in the array.

print(matrix.size)

Output:

6

Regardless of dimensions, size always gives the total element count.


The dtype Attribute

The dtype attribute shows the data type of elements stored in the array.

nums = np.array([1, 2, 3])
print(nums.dtype)

Output:

int64

NumPy automatically chooses the most efficient data type.


Changing the Data Type

You can explicitly specify or convert data types using dtype or astype().

float_arr = nums.astype(float)
print(float_arr)
print(float_arr.dtype)

Output:

[1. 2. 3.]
float64

This is useful when preparing data for scientific or machine learning tasks.


The itemsize Attribute

The itemsize attribute shows how many bytes each element occupies.

print(nums.itemsize)

Output:

8

This helps estimate memory usage for large datasets.


Practice Exercise

Exercise

Create a 2D NumPy array with 3 rows and 4 columns. Then print:

  • Number of dimensions
  • Shape of the array
  • Total number of elements
  • Data type

Expected Outcome

You should be able to inspect any NumPy array and understand its structure.


What’s Next?

In the next lesson, you will learn how to access specific elements using indexing and slicing.