NumPy Tutorial menu

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

python
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)
Output
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

dtypeMeaning
int32, int64Whole numbers (32 or 64 bits)
float32, float64Decimal numbers
boolTrue / False
complex128Complex numbers
<U + numberText strings

Choosing and Converting Types

Give a dtype when you create the array, or convert later with astype():

Example

python
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)
Output
[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

AttributeWhat it gives
shapeThe length of each dimension, as a tuple
ndimThe number of dimensions
sizeThe total number of items

Example

python
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)
Output
(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

python
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))
Output
[[ 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

python
import numpy as np
np.arange(10).reshape(3, 4)
Output
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

python
import numpy as np

grid = np.array([[1, 2], [3, 4]])
print(grid.flatten())
print(grid.T)
Output
[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?

Learn NumPy with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp