Truncate a NumPy float array to its integer part with astype(np.int64)
Quick Overview
Convert a NumPy array of positive floats into an int64 array of integer parts using astype. Tests how float-to-integer casts treat the fractional part, how that compares with flooring and rounding, and which inputs make the cast unsafe.
Truncate a NumPy float array to its integer part with astype(np.int64)
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `integer_part(a)` that takes a 1-D array of positive floats and returns its integer part as a new `int64` array via `arr.astype(np.int64)`. Values are truncated toward zero, not rounded (`3.9` becomes `3`).
Example:
```python
arr = np.array([1.2, 3.9, 4.5, 10.99])
integer_part(arr) # -> array([ 1, 3, 4, 10]), dtype int64
```
```hint Know the cast
Look at what a float-to-integer cast does with the fractional part, and check whether `astype` hands back a new array or changes the input in place.
```
### What a Strong Answer Covers
- Returns a new `int64` array with the fractional part dropped and leaves the input unchanged.
- Explains that the cast truncates toward zero and how that compares with flooring and rounding.
- Points out float representation surprises, where a value stored just below a whole number truncates down by one.
- Says which inputs the cast cannot represent (NaN, infinity, values outside the `int64` range) and how to guard against them.
### Follow-up Questions
- How would you round to the nearest integer instead of truncating, and what does NumPy do with values ending in .5?
- What changes for negative inputs, and how would you get floor semantics?
- How would you make the conversion fail loudly when the input holds NaN or out-of-range values?
Overview: Convert a NumPy array of positive floats into an int64 array of integer parts using astype. Tests how float-to-integer casts treat the fractional part, how that compares with flooring and rounding, and which inputs make the cast unsafe.
Write integer_part(a) that takes a 1-D array of positive floats and returns its integer part as a new int64 array via arr.astype(np.int64). Values are truncated toward zero, not rounded (3.9 becomes 3).