Convert object columns to the best nullable pandas dtypes
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `def best_dtypes(df: pd.DataFrame) -> pd.DataFrame` that returns `df.convert_dtypes()` to upgrade each all-`object` column to its best nullable dtype. The input has an integer-valued column with one missing entry, a column of `True`, `False` and `None`, and a free-text column. Every column starts as `object` dtype.
The result must meet these requirements:
- The integer column becomes `Int64`, with `pd.NA` for the missing entry.
- The boolean column becomes `boolean`, with `pd.NA` for `None`.
- The text column becomes `string` (`StringDtype`).
- The original index and column order are preserved.
Example:
```python
import pandas as pd
df = pd.DataFrame({
"n": pd.Series([1, 2, None], dtype=object),
"flag": pd.Series([True, False, None], dtype=object),
"text": pd.Series(["a", "b", "c"], dtype=object),
})
out = best_dtypes(df)
out.dtypes
# n Int64
# flag boolean
# text string
# dtype: object
```
Depending on the pandas version, the text dtype may print with its storage backend, for example `string[python]`.
```hint What the method looks at
Before trusting the one-liner, check what `convert_dtypes()` infers a type from in an `object` column: the Python type of each value, or the characters inside a string.
```
### Constraints & Assumptions
- Each column is `object` dtype and holds one kind of Python value plus `None`: `int`, `bool` or `str`.
- The values are clean, so no custom parsing or coercion is needed.
- pandas 1.0 or later, where `convert_dtypes()` exists.
### What a Strong Answer Covers
- A function that returns a new DataFrame from `convert_dtypes()` and leaves the input unchanged.
- The dtype each column ends up with and how its missing entry is represented.
- What `convert_dtypes()` infers a dtype from, and which inputs it leaves as `string` or `object`.
- A check of the result, such as `out.dtypes` and the missing cells.
### Follow-up Questions
- How does `convert_dtypes()` differ from `astype()` and `infer_objects()`?
- Why prefer the nullable `Int64` dtype over the default `float64` for integers with missing values?
- If the integer and boolean columns arrived as the strings `"1"`, `"2"`, `"True"` and `"False"` (plus `None`), what would `convert_dtypes()` return, and how would you get `Int64` and `boolean`?
Overview: Write a pandas function that upgrades object columns to nullable dtypes such as Int64, boolean and string while keeping the index and column order. It tests how pandas infers a dtype per column, how pd.NA represents missing values, and what that inference does with numbers stored as text.