NUMPY:Arrays, dtypes, and shape

Mastering arrays, dtypes, and shape concepts and implementation.

One block, two facts

Every NumPy array carries two facts you should be able to read out loud: its shape (how the numbers are arranged) and its dtype (what each number is). Most bugs in array code are one of those two facts being different from what you assumed.

import numpy as np

readings = np.array([
    [12.5, 13.1, 11.8],
    [14.0, 13.7, 12.9],
])

print(readings.shape)
print(readings.dtype)
print(readings.ndim)
print(readings.size)

Output:

(2, 3)
float64
2
6

Shape (2, 3) means 2 rows and 3 columns. ndim is the number of axes. size is the count of elements, not the memory size.

How arrays get made

import numpy as np

print(np.zeros((2, 3)))
print(np.ones(4))
print(np.arange(0, 10, 2))
print(np.linspace(0, 1, 5))

Output:

[[0. 0. 0.]
 [0. 0. 0.]]
[1. 1. 1. 1.]
[0 2 4 6 8]
[0.   0.25 0.5  0.75 1.  ]
  • zeros and ones take a shape. Pass a tuple for more than one axis.
  • arange is range for arrays: start, stop, step. The stop is excluded.
  • linspace(0, 1, 5) is five evenly spaced numbers from 0 through 1, and the stop is included.

Dtype is a choice

import numpy as np

whole = np.array([1, 2, 3])
mixed = np.array([1, 2, 3.5])
forced = np.array([1.9, 2.2, 3.8], dtype=np.int64)

print(whole.dtype, mixed.dtype)
print(forced)

Output:

int64 float64
[1 2 3]

A single float in the list promotes the whole array to float64. Forcing int64 truncates; it does not round. 3.8 becomes 3.

What to notice

  • Ask .shape and .dtype before you transform an array you did not create.
  • np.arange(5) is 0, 1, 2, 3, 4. The length is 5 because the stop is excluded.
  • Integer arrays cannot hold 3.5. If you need the fraction, the dtype has to be floating.

Try this

Create a 3 by 4 array of ones, then print its shape, dtype, and size. Change it to integers with .astype(np.int64) and print the dtype again.

Next: picking rows, columns, and the rows that pass a test, without writing a loop.