astype returns a new pandas Series with values converted to a specified data type. Because dtype is read-only, use astype rather than assigning directly to change an existing Series. section 1.5
Use astype when a data task requires a deliberate type change:
- Convert generated floating-point temperatures to compact integers, rounding first when fractional values should not be truncated. section 1.19
- Convert numeric values to strings for character-level extraction, then convert the cleaned result back to an integer dtype. section 1.11
- Convert cleaned percentage strings into floating-point values before sorting and plotting. section 11.2
- Choose a dtype that fits the data, since smaller numeric types can reduce memory consumption but inappropriate types can fail. section 1.5
Extracting and converting tens digits
For an integer Series s, chain s.astype(str).str.get(-2).fillna('0').astype(np.int8). This converts values to strings, retrieves the second-to-last character, replaces missing characters from one-digit numbers, and returns int8 values. section 1.11
(
s
.astype(str) # get a series based on s, with dtype str
.str.get(-2) # retrieve the second-to-last character
.fillna('0') # replace NaN with '0'
.astype(np.int8) # get a new series back dtype int8
)
Inspect the complete chained expression showing conversion to strings, character extraction, missing-value replacement, and conversion back to int8. section 1.11
