How does NumPy's astype work for casting arrays, and what are the safe/same_kind/unsafe casting rules?

Quick Overview

Asks how NumPy's astype converts an array to a new dtype and how the casting argument decides which conversions are allowed. Tests the copy behavior, the safe, same_kind and unsafe rules, silent truncation and overflow, and how to make risky casts fail early.

How does NumPy's astype work for casting arrays, and what are the safe/same_kind/unsafe casting rules?

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: medium

Interview Round: Other

How does `astype` work for casting NumPy arrays, and what are the `safe`/`same_kind`/`unsafe` casting rules? ```hint Check the default Look up the default value of the `casting` argument of `astype`, then ask what happens to a value like 1.7 cast to an integer under each rule. ``` ### What a Strong Answer Covers - What `astype` returns, when it copies, and which casting rule it uses by default. - The ordering of the casting rules and what each one allows, with an example for each. - What happens to values that do not fit the target dtype when the cast is unchecked. - How to make a risky cast fail loudly or check it ahead of time. ### Follow-up Questions - Why does `x += 1.5` fail on an integer array while `x = x + 1.5` works? - What do you get when you cast `np.nan`, or a float larger than the integer range, to an integer dtype? - NumPy treats `int64` to `float64` as a safe cast. Is it lossless for every value? - How would you convert floats to integers so that 2.9 becomes 3?

Overview: Asks how NumPy's astype converts an array to a new dtype and how the casting argument decides which conversions are allowed. Tests the copy behavior, the safe, same_kind and unsafe rules, silent truncation and overflow, and how to make risky casts fail early.

General logo
General
Nov 24, 2026
mediumData ScientistOtherData Manipulation (SQL/Python)
0
0

How does astype work for casting NumPy arrays, and what are the safe/same_kind/unsafe casting rules?

What a Strong Answer Covers Guidance

  • What astype returns, when it copies, and which casting rule it uses by default.
  • The ordering of the casting rules and what each one allows, with an example for each.
  • What happens to values that do not fit the target dtype when the cast is unchecked.
  • How to make a risky cast fail loudly or check it ahead of time.

Follow-up Questions Guidance

  • Why does x += 1.5 fail on an integer array while x = x + 1.5 works?
  • What do you get when you cast np.nan , or a float larger than the integer range, to an integer dtype?
  • NumPy treats int64 to float64 as a safe cast. Is it lossless for every value?
  • How would you convert floats to integers so that 2.9 becomes 3?