Lesson 02
Array Attributes
Read an array with ndim, shape, size, dtype, and itemsize, then change its type with astype and its layout with the shape attribute.
np.array() turns a list, a tuple, or a nested list into an ndarray. Once you have one, five attributes tell you what is inside: how many dimensions, the length of each, the total count, the element type, and the bytes per element.
Five attributes
ndim is the number of dimensions. shape is a tuple with the length of each dimension. size is the total number of elements. dtype is the element type, and itemsize is the bytes per element. The example fixes the dtype to int32 so the numbers match on every machine.
import numpy as np
m = np.array([[4, 7, 1], [9, 2, 6]], dtype=np.int32)
print(m)
print("ndim:", m.ndim)
print("shape:", m.shape)
print("size:", m.size)
print("dtype:", m.dtype)
print("itemsize:", m.itemsize)Output:
[[4 7 1]
[9 2 6]]
ndim: 2
shape: (2, 3)
size: 6
dtype: int32
itemsize: 4Without a dtype, whole numbers use the platform default. That is int64 on most desktops. The browser playground uses int32.
One, two, and three dimensions
A flat list gives a 1-D array, and its shape has one number followed by a comma. A list of rows gives 2-D. A list of 2-D blocks gives 3-D, and its shape reads as blocks, rows, columns.
import numpy as np
line = np.array([5, 6, 7])
table = np.array([[1, 2], [3, 4]])
blocks = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
for arr in (line, table, blocks):
print(arr.ndim, arr.shape, arr.size)Output:
1 (3,) 3
2 (2, 2) 4
3 (2, 2, 3) 12Change the type with astype
astype returns a new array with a different dtype. Turning floats into integers drops the decimal part. It does not round.
import numpy as np
readings = np.array([2.9, 4.1, 7.5])
print(readings.dtype)
whole = readings.astype(np.int32)
print(whole, whole.dtype)
print(readings)Output:
float64
[2 4 7] int32
[2.9 4.1 7.5]Change the layout with shape
Assigning a new tuple to shape changes the layout of that same array. reshape returns a new view and leaves the original alone. Either way, the new shape must hold exactly size elements.
import numpy as np
a = np.array([10, 20, 30, 40, 50, 60])
b = a.reshape(2, 3)
print(b)
print(a.shape)
a.shape = (3, 2)
print(a)Output:
[[10 20 30]
[40 50 60]]
(6,)
[[10 20]
[30 40]
[50 60]]Key takeaways
-
shapeis a tuple, and(3,)means a 1-D array of three -
sizeis the product of the numbers inshape -
astype(int)truncates decimals -
Assigning
shapechanges the array.reshapereturns a new view -
Next: Creating Arrays
-
Previous: What Is NumPy
Loading playground…
Check your understanding
Array Attributes Quiz
What is the shape of np.array([[1, 2, 3], [4, 5, 6]])?
1 / 10