= np.array([[1, 2, 3], [4, 5, 6]]) matrix
3 Size, Structure, and Type
If you’re unsure about the structure or shape of an array, or if you want to use this information for loops, NumPy offers the following functions to retrieve it:
np.shape()
returns the length of each dimension in the form of a tuple.
np.shape(matrix)
(2, 3)
The native Python function len()
only returns the length of the first dimension, i.e., the number of elements in the outer brackets. In the example above, len()
sees the two lists [1, 2, 3]
and [4, 5, 6]
.
len(matrix)
2
The function np.ndim()
returns the number of dimensions, unlike np.shape()
.
np.ndim(matrix)
2
np.ndim()
can also be derived using np.shape()
and a native Python function. How?
np.ndim()
simply returns the length of the tuple from np.shape()
:
len(np.shape(matrix))
2
If you want to know the total number of elements in an array, you can use the function np.size()
.
np.size(matrix)
6
NumPy arrays can contain various data types. Below we have three different arrays with different data types:
= np.array([1, 2, 3, 4, 5])
typ_a = np.array([0.1, 0.2, 0.3, 0.4, 0.5])
typ_b = np.array(["Monday", "Tuesday", "Wednesday"]) typ_c
With the method np.dtype
, we can retrieve the data type of arrays. Usually, this returns the type along with a number that represents the number of bytes needed to store the values. The array typ_a has the data type int64
, meaning whole numbers.
print(typ_a.dtype)
int64
The array typ_b has the data type float64
, where float represents floating-point numbers.
print(typ_b.dtype)
float64
The array typ_c has the data type U8
, where U
stands for Unicode. The text is stored in Unicode format.
print(typ_c.dtype)
<U9
Below is a table of typical data types you’ll commonly encounter in NumPy:
Data Type | NumPy Name | Examples |
---|---|---|
Boolean | bool |
[True, False, True] |
Integer | int |
[-2, 5, -6, 7, 3] |
Unsigned Integer | uint |
[1, 2, 3, 4, 5] |
Floating Point | float |
[1.3, 7.4, 3.5, 5.5] |
Complex Numbers | complex |
[-1 + 9j, 2 - 77j, 72 + 11j] |
Text (Unicode) | U |
[“monday”, “tuesday”] |
Given the following matrix:
= np.array([[[ 0, 1, 2, 3],
matrix 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[
12, 13, 14, 15],
[[16, 17, 18, 19],
[20, 21, 22, 23]],
[
24, 25, 26, 27],
[[28, 29, 30, 31],
[32, 33, 34, 35]]]) [
Visually determine the number of dimensions and the length of each dimension. What is the data type of the elements in this matrix?
Then verify your results by applying the appropriate NumPy functions.