All sample questions / pandas
What does print(s.astype(int)) print? pandas Series, Index and dtypes
Block 1, Series, Index and dtypes, question 2 of the pandas sample
import pandas as pd
s = pd.Series(['1', '2', 'x'])
print(s.astype(int))
What does this print?
Show the answer and why each option is right or wrong
Answer, A. ValueError
- A. ValueError
- Correct. astype(int) tries to convert every entry, and since 'x' cannot be parsed as an integer, the conversion fails for the whole Series and raises a ValueError rather than silently skipping or defaulting that one entry.
- B. nan
- Assumes the whole operation quietly produces a single missing value instead of raising an error.
- C. 0 1\n1 2\n2 NaN\ndtype: float64
- Assumes an unparseable entry becomes a missing float value while the dtype falls back to float64, rather than the conversion raising an error.
- D. 0 1\n1 2\n2 0\ndtype: int64
- Assumes an unparseable entry gets silently replaced by 0 while the rest convert normally.
astype(int) has no fallback for a value it cannot parse, it either converts every entry or raises. Unlike pd.to_numeric with errors='coerce', there is no way to ask astype to turn unparseable entries into missing values instead of failing.
The answer above is what pandas 3.0.5 printed when the snippet was run, not what someone expected it to do.
This question comes from a bank of 255 pandas interview questions, all built the same way, sold as one PDF with the full answer key.
Get the 255 pandas questions, 9 euros
Or SQL, Python, pandas and NumPy together, 1,636 questions, 19 euros
Or play the free pandas sample, twenty questions in the browser, also as a free PDF.
Previous question Next question
Did this save you a lookup? Buy me a coffee on Ko-fi.