NumPy Data Types and Shape
Every NumPy array has one data type for all its items, and a shape that describes its layout.
The dtype Attribute
dtype tells you the type of the values in an array:
Example
import numpy as np
a = np.array([1, 2, 3])
b = np.array([1.5, 2.0])
c = np.array(["Ali", "Sara"])
d = np.array([True, False])
print(a.dtype)
print(b.dtype)
print(c.dtype)
print(d.dtype)int64 float64 <U4 bool
<U4 means text (Unicode) of up to 4 characters. On some Windows systems you may see int32 instead of int64.
Common Data Types
| dtype | Meaning |
|---|---|
int32, int64 | Whole numbers (32 or 64 bits) |
float32, float64 | Decimal numbers |
bool | True / False |
complex128 | Complex numbers |
<U + number | Text strings |
Choosing and Converting Types
Give a dtype when you create the array, or convert later with astype():
Example
import numpy as np
a = np.array([1, 2, 3], dtype="float64")
print(a)
prices = np.array([99.9, 150.5, 20.2])
whole = prices.astype(int)
print(whole)
print(whole.dtype)[1. 2. 3.] [ 99 150 20] int64
astype() returns a new array. Like Python's int(), converting to int cuts off the decimal part.
If you mix numbers and text in one array, NumPy turns everything into text. Keep each array to one kind of data.
Shape and Size
| Attribute | What it gives |
|---|---|
shape | The length of each dimension, as a tuple |
ndim | The number of dimensions |
size | The total number of items |
Example
import numpy as np
sales = np.array([
[1200, 1500, 900, 1100],
[1300, 1700, 1000, 1250],
[1100, 1400, 950, 1050]
])
print(sales.shape)
print(sales.ndim)
print(sales.size)(3, 4) 2 12
Shape (3, 4) means 3 rows and 4 columns.
Reshaping
reshape() gives the same data a new shape. The total number of items must stay the same.
Example
import numpy as np
arr = np.arange(1, 13)
print(arr.reshape(3, 4))
print(arr.reshape(2, 2, 3).shape)
print(arr.reshape(2, -1))[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] (2, 2, 3) [[ 1 2 3 4 5 6] [ 7 8 9 10 11 12]]
Use -1 for one dimension and NumPy works it out for you. Here 12 items in 2 rows means 6 columns.
Trying an impossible shape gives an error:
Example
import numpy as np
np.arange(10).reshape(3, 4)ValueError: cannot reshape array of size 10 into shape (3,4)
Flattening
To turn any array back into 1-D, use flatten() (a copy) or ravel() (a view when possible):
Example
import numpy as np
grid = np.array([[1, 2], [3, 4]])
print(grid.flatten())
print(grid.T)[1 2 3 4] [[1 3] [2 4]]
.T gives the transpose: rows become columns and columns become rows.
Exercise
Exercise
An array has shape (4, 5). What is its size?
