Sub topic 2
NumPy dtypes: fixed-width values in contiguous arrays
This chapter assumes you can create a DataFrame and select columns, and that you know Python's int, float and str. NumPy experience helps but is not required. By the end you should be able to read a dtype, say how many bytes a column's values take, and predict where numeric types overflow, lose precision or get promoted.
A column is an array with one dtype
Every column in a DataFrame is backed by an array of values that all have the same type. That type is the column's dtype (data type). For most numeric, boolean and datetime columns, the array is a NumPy ndarray.
import pandas as pd
df = pd.DataFrame({
"a": [1, 2, 3],
"b": [1.5, 2.5, 3.5],
"c": ["x", "y", "z"],
})
print(df.dtypes)In pandas 2.x this prints int64 for a, float64 for b and object for c. Column c is not a fixed-width type. The next chapter covers it. Newer pandas versions may show a dedicated string dtype for c instead.
A dtype tells NumPy three things:
- Kind: integer, unsigned integer, float, boolean, datetime, timedelta, or a generic Python object.
- Width: how many bytes each value occupies. This is the
itemsize. - Byte order: how the bytes of one value are arranged. You rarely need to think about this on common hardware.
Fixed-width values in one contiguous buffer
A NumPy array stores its values back to back in a single block of memory. Every value takes exactly itemsize bytes, so value number i starts at byte i * itemsize. NumPy can find any element with one multiplication and no pointer lookup. That is why vectorized operations such as s + 1 or s.sum() run in compiled loops over raw memory.
import numpy as np
import pandas as pd
s = pd.Series(np.arange(1_000_000, dtype="int64"))
arr = s.to_numpy()
print(arr.dtype, arr.shape)
print(arr.itemsize, arr.nbytes)
print(arr.strides, arr.flags["C_CONTIGUOUS"])
print(s.memory_usage(index=False))The output is:
int64 (1000000,)
8 8000000
(8,) True
8000000itemsizeis 8 bytes per value.nbytesisitemsize * len, which is 8,000,000 bytes.stridesis the number of bytes to jump to reach the next element, and(8,)means the values are packed with no gaps.memory_usage(index=False)agrees withnbytes, because for a fixed-width column the values are the whole story.
The fixed width has a cost. The column's memory is n * itemsize whatever the data holds. A column of a million 1s and a column of a million large numbers both take 8 MB as int64. Choosing a narrower dtype is the main way to shrink such a column, and the downcasting chapter returns to it.
The common NumPy dtypes in pandas
| Dtype | Bytes per value | What it holds | Range or precision |
|---|---|---|---|
| `int8` | 1 | signed integers | -128 to 127 |
| `int16` | 2 | signed integers | -32,768 to 32,767 |
| `int32` | 4 | signed integers | about ±2.1 billion |
| `int64` | 8 | signed integers | about ±9.2 × 10^18 |
| `uint8` | 1 | unsigned integers | 0 to 255 |
| `float32` | 4 | floating-point numbers | about 7 significant digits |
| `float64` | 8 | floating-point numbers | about 15 to 16 significant digits |
| `bool` | 1 | True or False | 1 byte per value, not 1 bit |
| `datetime64[ns]` | 8 | timestamps | nanosecond resolution |
| `timedelta64[ns]` | 8 | durations | nanosecond resolution |
You can write a dtype several ways: "int64", np.int64, or the short code "i8" (kind plus byte count). Prefer the full names in code you share, since they are easier to read.
Default inference
When you build a column from Python values, pandas picks the widest common default:
- Whole numbers become
int64. - Numbers with a decimal part become
float64. TrueandFalsebecomebool.- Strings become
objectin pandas 2.x. - Date strings stay strings until you convert them with
pd.to_datetime.
The defaults favor safety over size. They rarely overflow, but they are often wider than your data needs.
Integers: exact, but with a limited range
Integer dtypes are exact within their range and wrap around outside it. NumPy does not raise an error when an integer operation overflows, so the result is silently wrong.
import numpy as np
import pandas as pd
info = np.iinfo("int8")
print(info.min, info.max)
s = pd.Series([100, 120, 127], dtype="int8")
print(s + 1)
print(np.array([200]).astype("int8"))The results are:
iinfoprints-128 127.s + 1gives101,121and-128. The value 127 plus 1 wrapped to the bottom of the range.- The
astype("int8")call turns 200 into-56, because 200 - 256 = -56.
Unsigned integers (uint8 and wider) cannot hold negative numbers. Subtracting a larger value from a smaller one wraps to a huge positive number. Use them only for data that cannot be negative, such as counts, ids and pixel values.
Floats: approximate by design
Floating-point dtypes follow the IEEE 754 standard. They store a sign, an exponent and a fraction, so most decimal fractions are only approximated.
import numpy as np
print(0.1 + 0.2 == 0.3)
print(np.isclose(0.1 + 0.2, 0.3))
print(np.float32(16_777_216) + np.float32(1))This prints False, True and 16777216.0:
- The first line is
Falsebecause0.1 + 0.2is slightly more than0.3in binary. Compare floats withnp.isclose, not==. - The last line shows
float32running out of precision. Above 2^24 = 16,777,216, afloat32cannot represent every integer, so adding 1 changes nothing.
float32 halves the memory of float64 but keeps only about seven significant digits. It suits measurements and model inputs. It is a poor fit for money, large ids stored as numbers, or long running sums. Floats also have special values: NaN (not a number) and inf. The next chapters use NaN as pandas's default marker for a missing number.
Booleans: one byte each
A bool column stores one byte per value, not one bit. A million flags take a million bytes. That is still the smallest dtype pandas offers for yes/no data, and it is 8 times smaller than storing the same flags as int64.
Datetimes: integers with a unit
NumPy stores a datetime64[ns] value as an int64 count of nanoseconds since 1970-01-01 (the Unix epoch). The dtype adds the meaning, and the buffer is an ordinary 8-byte integer array.
import pandas as pd
idx = pd.to_datetime(["1970-01-02"]).astype("datetime64[ns]")
s = pd.Series(idx)
print(s.dtype)
print(s.to_numpy().view("int64"))The output is datetime64[ns] and [86400000000000]. That is one day expressed in nanoseconds. The .astype("datetime64[ns]") call pins the unit, because newer pandas versions can pick a coarser one such as microseconds. Because the storage is a plain integer, comparing and subtracting timestamps are fast integer operations. A timedelta64[ns] column works the same way.
Promotion: mixing dtypes in one operation
When an operation combines two dtypes, NumPy picks a result dtype that can hold both. This is called type promotion. Pandas follows the same rules:
int64 + int64staysint64.int64 + float64givesfloat64.int8 + int64givesint64, the wider of the two.bool + int64givesint64.
import pandas as pd
ints = pd.Series([1, 2, 3])
print((ints + 0.5).dtype)
print((ints > 1).dtype)
print(pd.concat([ints, pd.Series([1.5])]).dtype)The three results are float64, bool and float64. The last line matters in practice. Concatenating or joining frames can silently turn an integer column into floats if one side holds floats. Large int64 values lose exactness when they become float64, because a float64 keeps only about 15 to 16 significant digits.
Common errors and how to avoid them
- Assuming an integer is 32-bit. Pandas defaults to
int64. On Windows with NumPy 1.x, a barenp.arange(5)can beint32, so passdtype="int64"when you need a specific width. - Trusting a narrow dtype's arithmetic. Sums and products of
int8oruint8columns can overflow even if every input fits. Cast to a wider dtype before heavy arithmetic, or letsum()do it. Pandas aggregations accumulate in a wider type for small integers. - Comparing floats with
==. Usenp.iscloseor compare after rounding. - Treating
objectas "string". Anobjectcolumn holds pointers to Python objects, not text. It can hold anything, so it gets none of the speed or compactness of the fixed-width dtypes. - Reading dtypes off a few rows. Inference looks at the data it sees. A column that is
int64in one file can befloat64orobjectin another if the data differs. - Expecting
boolto be compact. It is 1 byte per value. If you need bit-level storage, that is outside what a pandas column offers.
Inspecting dtypes in practice
These checks answer most dtype questions:
df.dtypesshows the dtype of every column.s.dtypeshows one column's dtype.s.to_numpy().itemsizegives the bytes per value.np.iinfo(dtype)andnp.finfo(dtype)report the range of an integer type or the precision of a float type.df.select_dtypes("number")picks the columns of a given kind.
What comes next
Fixed-width dtypes give pandas its speed and a predictable size, but they cannot hold everything. Strings and mixed values need a different storage scheme, the object dtype, which the next chapter describes. After that, missing values show why int64 columns sometimes turn into float64.
Exercise
A column of ages (0 to 120) is stored as int64 with 5,000,000 rows. How many bytes does the values buffer take? Which NumPy dtype is the smallest that fits the data, and how many bytes would it take? Why might astype("int8") be a bad choice here if any age could be 130?
Show answer
The buffer takes 5,000,000 × 8 = 40,000,000 bytes (40 MB). Ages up to 120 fit in int8 (range -128 to 127) or uint8 (0 to 255). Either takes 5,000,000 × 1 = 5,000,000 bytes, and uint8 is the natural choice since ages are never negative. If any age could be 130, int8 would wrap that value to a negative number without raising an error (130 - 256 = -126). uint8 would hold 130, but you should still check min() and max() before casting.
Exercise
Predict the dtype of pd.Series([True, False]) + pd.Series([1, 2]), and then of pd.Series([1, 2]) / 2. Explain each in terms of dtype promotion.
Show answer
The first is int64: the bool values are promoted to integers (True becomes 1, False becomes 0) and added to the int64 values, giving 2 and 2. The second is float64: true division of integers produces floating-point results (0.5 and 1.0), so the result dtype is promoted to float64 even though the second value is a whole number.