Sub topic 5
Setting data types at load time
This chapter covers how read_csv decides on column types, why those guesses sometimes go wrong, and how to override them. It assumes you can run Python scripts or notebooks, have pandas installed, and know what a DataFrame is. The examples read small in-memory strings with StringIO, so you can run each one as shown.
How pandas infers types
A CSV file is plain text. It has no type information, so every value starts as a string. When you call read_csv, pandas looks at each column and tries to convert it to the narrowest type that fits all of its values.
The rules, in simplified form:
- If every value parses as an integer, the column becomes
int64. - If values parse as numbers but some have decimals or are missing, the column becomes
float64. - If values are
True/False(in a few spellings), the column becomesbool. - Anything else becomes
object, which holds Python strings.
Dates are not converted by default. They stay object unless you ask for parsing, which a later chapter covers.
import pandas as pd
from io import StringIO
text = "id,score,passed,name\n1,9.5,True,Ana\n2,7.0,False,Ben\n"
df = pd.read_csv(StringIO(text))
print(df.dtypes)The output shows int64, float64, bool and object. Inference works well for clean data. The trouble starts when the data is not clean, or when the text looks like a number but is not one.
Where inference goes wrong
Three failures show up again and again.
Leading zeros disappear. ZIP codes, phone numbers and product codes are identifiers, not quantities. Inference sees digits and converts them to integers, which drops the leading zero. 02134 becomes 2134. The original text cannot be recovered afterward.
One bad value changes a whole column. A single entry such as n/a or unknown in a numeric column makes the whole column object, and arithmetic on it then fails or gives surprising results.
Integers become floats when values are missing. The default int64 type has no way to represent a missing value. If a column of integers contains one blank cell, pandas converts the entire column to float64 and the integers become 1.0, 2.0 and so on.
import pandas as pd
from io import StringIO
text = "zip,count\n02134,5\n10001,\n"
df = pd.read_csv(StringIO(text))
print(df["zip"].tolist())
print(df["count"].dtype)This prints [2134, 10001] and float64. Both results are probably not what you wanted.
Overriding types with dtype
The dtype argument tells pandas what type to use. Pass a dictionary that maps column names to types. Columns you do not mention still use inference.
import pandas as pd
from io import StringIO
text = "zip,city,notes\n02134,Boston,a\n10001,New York,b\n"
df = pd.read_csv(
StringIO(text),
usecols=["zip", "city"],
dtype={"zip": "string"},
)
print(df["zip"].tolist())The result is ['02134', '10001']. The leading zero survives because pandas never converts the text to a number. The usecols argument, covered in the previous chapter, skips the notes column.
You can also pass a single type to apply to every column.
import pandas as pd
from io import StringIO
text = "a,b\n001,002\n003,004\n"
df = pd.read_csv(StringIO(text), dtype=str)
print(df)Reading everything as str is a useful first step with messy files. You get the raw text and can then convert columns one at a time, with full control over how failures are handled.
Common type names
| Type name | What it holds | Missing values |
|---|---|---|
| `"int64"` | 64-bit integers | Not allowed. Raises an error. |
| `"Int64"` | Nullable integers | Allowed, shown as `<NA>` |
| `"float64"` | Floating-point numbers | Allowed, stored as `NaN` |
| `"bool"` | True or False | Not allowed |
| `"boolean"` | Nullable booleans | Allowed |
| `"string"` | Text, using pandas' string type | Allowed |
| `"category"` | A fixed set of repeated values | Allowed |
| `str` or `object` | Python strings in a general container | Allowed |
Notice that some names differ only in capitalization. "int64" with a lowercase i is the NumPy type. "Int64" with a capital I is the pandas nullable type. They behave differently, and mixing them up is a common mistake.
Nullable integers
To keep a column of integers as integers when some values are missing, use the capitalized Int64 type.
import pandas as pd
from io import StringIO
text = "id,count\n1,5\n2,\n3,7\n"
df = pd.read_csv(StringIO(text), dtype={"count": "Int64"})
print(df["count"].tolist())
print(df["count"].dtype)The missing value appears as <NA> and the other values stay 5 and 7, not 5.0 and 7.0. The same pattern works for "Int32", "Float64" and "boolean".
If you ask for plain "int64" and the column has a blank cell, pandas raises an error because it cannot convert the missing value. That error is useful. It tells you the data has gaps you need to decide about.
Strings: object versus string
The default text type is object, a general container that can hold any Python value. It works, but it cannot tell you whether a column contains only text. Asking for "string" gives you the dedicated pandas string type. It holds only text and missing values, and it reports a clear type name.
import pandas as pd
from io import StringIO
text = "name\nAna\nBen\n"
as_object = pd.read_csv(StringIO(text))
as_string = pd.read_csv(StringIO(text), dtype={"name": "string"})
print(as_object["name"].dtype)
print(as_string["name"].dtype)For most analysis the difference does not matter. Prefer "string" when you want type checks to be meaningful, for example when a column should never contain numbers by accident.
Categories for repeated values
Some columns contain a small set of values repeated many times, such as country codes or order status. The "category" type stores each distinct value once and keeps small integer codes for the rows. This reduces memory use and can speed up grouping.
import pandas as pd
from io import StringIO
text = "status\nshipped\nshipped\npending\nshipped\n"
df = pd.read_csv(StringIO(text), dtype={"status": "category"})
print(df["status"].dtype)
print(df["status"].cat.categories.tolist())
print(df.memory_usage(deep=True))Use category when the number of distinct values is small compared with the number of rows. For a column where almost every value is unique, such as a name or an email address, the category type saves nothing.
Converting values with converters
Sometimes a type name is not enough because the text needs cleaning first. The converters argument takes a dictionary that maps a column name to a function. pandas calls the function on each raw string in that column.
import pandas as pd
from io import StringIO
text = "item,price\nbook,$12.50\npen,$1.20\n"
df = pd.read_csv(
StringIO(text),
converters={"price": lambda s: float(s.replace("$", ""))},
)
print(df["price"].sum())The result is 13.7. Converters run in Python for every value, so they are slower than dtype on large files. Use dtype when a type name is enough, and keep converters for cases that need real cleanup. If a column appears in both dtype and converters, pandas uses the converter and warns that dtype is ignored.
Memory-saving types
Defaults are generous. An int64 uses 8 bytes per value even when the numbers are small. If a column only holds values from 0 to 100, "int8" uses 1 byte.
import pandas as pd
from io import StringIO
text = "age\n25\n31\n47\n"
default = pd.read_csv(StringIO(text))
small = pd.read_csv(StringIO(text), dtype={"age": "int8"})
print(default["age"].memory_usage(index=False))
print(small["age"].memory_usage(index=False))Choose a smaller type only when you know the range of the data. An int8 holds values from -128 to 127. If the file contains a larger number, pandas raises an error instead of silently wrapping, which is the behavior you want.
When it fails: converting after the fact
Sometimes you cannot set a type at load time, because the file contains stray text in a numeric column. The load fails with a ValueError, or you read the column as strings and convert later. The function pd.to_numeric does the second job and lets you choose what happens to bad values.
import pandas as pd
from io import StringIO
text = "id,amount\n1,10\n2,unknown\n3,30\n"
df = pd.read_csv(StringIO(text), dtype={"amount": "string"})
df["amount"] = pd.to_numeric(df["amount"], errors="coerce")
print(df)
print(df["amount"].isna().sum())With errors="coerce", values that cannot be converted become NaN, and you can count them. The default, errors="raise", stops at the first bad value. Prefer coerce followed by a check on how many values failed. Silently ignoring failures hides data problems.
Mixed-type warnings
For large files, pandas may read the file in internal pieces and infer a type for each piece. If one piece looks numeric and another has text, you can get a DtypeWarning about mixed types, and the column ends up holding both numbers and strings. The fix is to set dtype explicitly for that column. Setting low_memory=False also makes pandas infer once over the whole file, but it uses more memory, and an explicit dtype is the more reliable choice.
Decision guide
Checking the result
After loading with explicit types, confirm that they took effect. Call df.dtypes for a compact view, or df.info() for types plus non-null counts. If a column you expected to be Int64 shows float64, the type name was probably misspelled in the dictionary, such as a column name that does not match the header exactly. Names in dtype that do not exist in the file are ignored without an error, so check the spelling.
Exercise
A CSV has columns sku (values like 00123), qty (integers, with some blank cells) and region (only "north", "south" or "west", repeated across a million rows). Write the dtype dictionary you would pass to read_csv, and say why each type was chosen.
Show answer
dtype={"sku": "string", "qty": "Int64", "region": "category"}. sku is an identifier, so string keeps the leading zeros. qty has blanks, so the nullable Int64 keeps integers instead of converting to float64. region has three distinct values repeated many times, so category saves memory.
Exercise
A column amount contains the values 10, 20 and the word unknown. You load it with dtype={"amount": "string"}. How do you convert it to numbers and find out how many values were bad?
Show answer
Use df["amount"] = pd.to_numeric(df["amount"], errors="coerce"), which turns unknown into NaN. Then call df["amount"].isna().sum() to count the values that failed to convert. In this example the count is 1.