Array Errors
Most early NumPy errors are shape errors, dtype surprises, or index errors.
The fix is rarely to guess. Print the shape and dtype first.
Shape mismatch
Elementwise operations need compatible shapes.
This fails because the arrays do not line up.
A shape mismatch
Ready to run.
You will learn broadcasting later. For now, use the simple rule: when elementwise operations fail, inspect both shapes.
Dtype surprise
If one value is text, NumPy may create a string array:
That can make later numerical operations confusing. Keep input data clean and
convert near the boundary. NumPy does not silently turn that text back into a
number merely because it contains the character 3.
Index error
Array indexing follows the same boundary rule as lists:
There are three values, but the last valid positive index is 2.
The debugging checklist
When an array operation fails:
- print each relevant shape;
- print each relevant dtype;
- make the array smaller;
- try the operation again;
- explain what each axis means.
When an elementwise array operation fails, what should you inspect first?
Answer it first, then check.
Hint
Ask whether corresponding positions can line up. The relevant property is a
tuple such as (3,).
Solution
Inspect each array's shape first. The shapes show whether the operands can line up and often explain an elementwise-operation error immediately. Inspect dtype next if the shapes are compatible but the values still behave oddly.