Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 49 ยท Data Types

Converting and Casting Types

Convert NumPy dtypes with astype, learn how view differs, how casting rounds, how NumPy 2 promotion (NEP 50) works, and read finfo and iinfo limits.

Sooner or later you need a different dtype: floats read from a file that should be integers, a mask that must become 0 and 1, an image that needs a wider type before arithmetic. NumPy calls this casting. It also converts types automatically when you mix them in one expression, which is called type promotion.

This lesson covers explicit conversion with astype, how it differs from view, what happens to decimals, how np.can_cast predicts safety, the promotion rules (including the NumPy 2 changes known as NEP 50), and the limits of floating-point precision.

astype makes a converted copy

arr.astype(new_dtype) returns a new array with converted values. The original is untouched.

Python astype basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at b: casting float to integer truncates toward zero, so 1.9 becomes 1 and -3.7 becomes -3. It does not round. If you want rounding, call np.round (or np.rint) first.

Python Truncate, round, floor and ceil

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that np.rint(2.5) gives 2 and np.rint(-2.5) gives -2. NumPy rounds halves to the nearest even number, the standard "banker's rounding" for floating point.

Casting can also fail. Strings that look like numbers convert, but others raise ValueError. Casting nan or inf to an integer produces an undefined value and a RuntimeWarning, so clean your data first (see Missing Data and NaN).

Python Strings and booleans

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Any nonzero number becomes True when cast to bool, and True becomes 1 going the other way.

view reinterprets the same bytes

arr.view(new_dtype) does not convert anything. It looks at the same memory through a different dtype lens, so the numbers change meaning. It is fast and occasionally useful, but easy to misuse.

graph LR
    M["the same 4 bytes in memory"] --> A["astype(float32)<br/>converts the number"]
    M --> V["view(uint8)<br/>reads bytes as they are"]

astype converts values into a new array; view reinterprets existing bytes without copying.

Python view versus astype

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The view has eight elements, four bytes for each int32, and changing a changes the view. The exact byte order depends on the machine (little-endian on nearly all modern hardware). Use astype when you want numbers converted and view only when you deliberately want to see raw bytes.

Can this cast happen safely?

np.can_cast(from, to, casting="safe") answers whether every value of one type fits in another. The modes are "no", "equiv", "safe" (the default), "same_kind" and "unsafe".

Python np.can_cast

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

"safe" means no value can be lost. "same_kind" also allows downcasts within a kind (float64 to float32). "unsafe" allows anything. In-place operators use same_kind as a guard, which explains an error you will meet in the pitfalls lesson: int_array += 1.5 raises a UFuncTypeError.

Type promotion in mixed operations

When you combine two arrays of different dtypes, NumPy promotes both to a common type that can hold both. np.result_type shows the answer without computing anything.

Python np.result_type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Some surprises: int32 plus float32 becomes float64 (a float32 cannot represent every int32 exactly), and uint64 with int64 also becomes float64 because no integer type fits both.

NumPy 2 and NEP 50: Python numbers are weak

NumPy 2 changed how plain Python numbers take part in promotion. A Python int or float is now "weak": it adapts to the array's dtype instead of pushing the result to a bigger type. The array's dtype wins.

Python Python scalars are weak in NumPy 2

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Before NumPy 2, the value of a Python scalar sometimes changed the result dtype; now only its kind (int, float, complex) matters. The result is simpler: array_uint8 + 5 stays uint8, and an out-of-range Python integer raises OverflowError instead of silently picking a wider type. NumPy scalars such as np.int64(5) carry a dtype and are not weak, so they promote normally.

Warning: Old tutorials describe value-based casting, where np.uint8(1) + 300 could give a larger type. That behavior was removed in NumPy 2. If your old code relied on it, cast explicitly with astype.

Float precision: finfo and iinfo

Floats are approximations. np.finfo(dtype) reports their limits and np.iinfo(dtype) does the same for integers.

Python finfo and iinfo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

eps is the gap between 1.0 and the next representable number: a rough measure of relative precision. A float32 has about 7 correct decimal digits, so past 16,777,216 it can no longer count by ones, and adding 1 changes nothing. Compare floats with a tolerance (see Comparing Arrays and Floating Point), never with ==.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is np.array([2.9, -2.9]).astype(int)?

    astype truncates toward zero, so 2.9 becomes 2 and -2.9 becomes -2. Use np.rint first if you want rounding.
  2. 2. What does arr.view(np.uint8) do to an int32 array?

    view shares memory and only changes how the bytes are read, so an int32 array of n items becomes a uint8 array of 4n items.
  3. 3. In NumPy 2, what is the dtype of np.array([1, 2], dtype=np.uint8) + 5?

    A Python int is weak (NEP 50), so it adopts the array dtype and the result stays uint8.
  4. 4. What is np.result_type(np.int32, np.float32)?

    float32 cannot hold every int32 exactly, so NumPy promotes both to float64.
  5. 5. What does np.can_cast(np.float64, np.float32) return with the default casting mode?

    The default mode is safe, and float64 to float32 can lose precision. The reverse direction, float32 to float64, returns True.

Summary

  • astype returns a converted copy; float to int truncates toward zero, so round first if needed.
  • view reinterprets the same memory and shares data with the original.
  • np.can_cast and np.result_type tell you in advance what will happen.
  • NumPy 2 (NEP 50): Python scalars are weak and keep the array's dtype; NumPy scalars are not weak.
  • np.finfo and np.iinfo give limits; never compare floats with ==.

Next: Indexing and Slicing