FAQ and Gotchas
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
This page was checked in October 2026 against pandas 3.1 (3.1.0, released 2026-10-22) on Python 3.13 with NumPy 2.5, and the printed output of every example was produced on those versions. It collects the behaviours that surprise people most often, starting with the entries of the official FAQ and continuing with the pitfalls that the pandas 3 defaults introduced. Each section states the symptom, the reason and the fix.
Truth values, in and labels versus positions
A Series has no single truth value
A Series holds many values, so if ser:, and, or and not cannot decide what you mean and raise a ValueError. State the question with any(), all(), empty or item(). Combining masks needs the element-wise operators &, | and ~, each condition in parentheses, not the keywords.
in tests the index
On a Series, in looks in the index, and on a DataFrame it looks in the column names. To ask whether a value is present, use isin and then any(). Comparisons with == and != are element-wise and return a boolean Series.
Labels and positions are different questions
ser[0] is a label lookup, so on a string index it raises KeyError. The positional fallback that older versions allowed for [] is gone; use iloc for positions. A related trap is slicing: loc slices include the stop label, iloc slices exclude the stop position.
import pandas as pd
s = pd.Series([1, 2, 3], index=["a", "b", "c"])
# Truth value of a Series is ambiguous
try:
if s:
pass
except ValueError as exc:
print("ValueError:", exc)
print(s.any(), s.all(), s.empty)
# `in` tests the index, not the values
print("b" in s, 2 in s)
print(s.isin([2]).any())
# Integer keys on a string index are labels, not positions
try:
s[0]
except KeyError as exc:
print("KeyError:", exc)
print(s.iloc[0], s.iloc[-1])
# loc slices include the stop label, iloc slices do not
x = pd.Series(range(5))
print(x.loc[1:3].tolist(), x.iloc[1:3].tolist())
Output:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.item(), a.any() or a.all(). True True False True False True KeyError: 0 1 3 [1, 2, 3] [1, 2]
See Indexing and Selecting for the full rules.
Mutating inside user-defined functions
DataFrame.apply, aggregate, transform and filter iterate over the object internally. A function that changes the row or column it receives, for example with pop, can remove something pandas is about to read, and the call fails with a confusing KeyError. Copy inside the function, or better, return a new value instead of editing the argument. Copy-on-Write does not change this, because the problem is the iteration, not the sharing of data. The same advice applies to plain Python loops that modify the container they iterate over: iterate over a copy.
import pandas as pd
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
def bad(row):
row.pop("a") # mutates the row that pandas is iterating over
return row
try:
df.apply(bad, axis="columns")
except KeyError as exc:
print("KeyError:", exc)
def good(row):
row = row.copy()
row.pop("a")
return row
print(df.apply(good, axis="columns"))
Output:
KeyError: 'a' b 0 3 1 4
Missing values and dtype promotion
NumPy integer and boolean arrays have no bit pattern that means "missing", so introducing a missing value changes the dtype. The promotion table is:
| Original dtype class | Result after a missing value appears |
|---|---|
floating |
no change ( |
object |
no change |
integer |
cast to |
boolean |
cast to |
That is why reindex, an outer merge, shift or an unaligned arithmetic operation can turn an integer column into floats. There are three remedies: use a nullable dtype (Int64, Float64, boolean) that stores a mask next to the values, use a PyArrow-backed dtype such as "int64[pyarrow]", or accept floats and cast after filling. Casting a column that still contains missing values to a NumPy integer dtype raises IntCastingNaNError.
Comparisons with missing values behave as in IEEE arithmetic: NaN is not equal to itself, so ser == np.nan is all False; use isna() and notna(). The scalar pd.NA propagates through comparisons (pd.NA == 1 is NA) and refuses to be used as a condition.
import numpy as np
import pandas as pd
ints = pd.Series([1, 2, 3], index=["a", "b", "c"])
widened = ints.reindex(["a", "b", "f"])
print(widened.dtype, widened.tolist())
nullable = ints.astype("Int64").reindex(["a", "f"])
print(nullable.dtype, nullable.tolist())
flags = pd.Series([True, False]).reindex([0, 5])
print(flags.dtype)
try:
pd.Series([1, np.nan]).astype("int64")
except Exception as exc:
print(type(exc).__name__)
print(np.nan == np.nan, pd.Series([np.nan]).eq(np.nan).tolist(), pd.NA == 1)
try:
bool(pd.NA)
except TypeError as exc:
print("TypeError:", exc)
Output:
float64 [1.0, 2.0, nan] Int64 [1, <NA>] object IntCastingNaNError False [False] <NA> TypeError: boolean value of NA is ambiguous
See Missing Data and Nullable Integer and Boolean.
Integer overflow and numeric differences
pandas stores integers in fixed-width NumPy types, int64 by default, and arithmetic wraps around silently when a result does not fit. There is no error, which makes an overflowing prod() or cumsum() easy to miss. For exact results, convert to object (Python integers have arbitrary precision, at a large speed cost); float64 avoids the wraparound but loses precision beyond about 15 digits. Narrow dtypes such as int8 wrap much sooner.
Two differences from NumPy matter in statistics code. Series.var() and std() use the sample formula (divide by N - 1, ddof=1), while numpy.var() and numpy.std() divide by N by default (ddof=0). cov() normalises by N - 1 in both libraries. Pass ddof explicitly whenever the two libraries meet. Also, NumPy functions called on pandas objects may pass extra arguments such as out or keepdims; pandas accepts them only at their default values, so use the documented arguments of the pandas method.
import numpy as np
import pandas as pd
big = pd.Series(range(1, 25))
print(big.prod()) # silently wrapped around
print(big.astype(object).prod()) # exact, arbitrary precision
small = pd.Series([100, 100], dtype="int8")
print((small + small).tolist())
values = [1.0, 2.0, 3.0, 4.0]
print(pd.Series(values).var(), np.var(values), np.var(values, ddof=1))
Output:
-7835185981329244160 620448401733239439360000 [-56, -56] 1.6666666666666667 1.25 1.6666666666666667
Floating-point equality has the usual caveat as well: 0.1 + 0.2 == 0.3 is False, so compare with np.isclose or pd.testing.assert_frame_equal (which has tolerances) instead of ==. The NumPy page Floating-Point Errors explains why.
Memory usage
DataFrame.info() prints memory in binary units (1 KB is 1024 bytes). For columns with the object dtype the default figure counts only the pointers, not the Python objects they point to, and the number is flagged with a plus sign (for example 284.1+ KB). info(memory_usage="deep") inspects the objects and gives the true figure, at the cost of a slower call, and memory_usage(deep=True) returns the per-column breakdown in bytes including the index (use index=False to leave the index out).
With the pandas 3 str dtype and PyArrow installed, strings are stored in Arrow buffers, so the quick figure and the deep figure agree and no plus sign appears; without PyArrow the str dtype falls back to Python objects and deep matters again. Repeated strings shrink dramatically as category.
import pandas as pd
df = pd.DataFrame({"name": ["a", "b"] * 1000, "n": range(2000)})
df.info(memory_usage="deep")
print(df.memory_usage(deep=True))
df["name"] = df["name"].astype("category")
print(df.memory_usage(deep=True).sum())
Output (PyArrow installed):
<class 'pandas.DataFrame'> RangeIndex: 2000 entries, 0 to 1999 Data columns (total 2 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 name 2000 non-null str 1 n 2000 non-null int64 dtypes: int64(1), str(1) memory usage: 33.3 KB Index 132 name 18000 n 16000 dtype: int64 18151
See Scaling to Large Datasets for dtype choices, chunking and out-of-core options.
Lists inside cells
A column of Python lists has the object dtype, uses much more memory than a native column and cannot use vectorised code. Lists are unhashable, so they cannot be group or merge keys, and methods that hash values, such as drop_duplicates(), raise TypeError. Prefer the long format with explode (one row per element, natively typed after infer_objects()), and rebuild lists at the end with agg(list) if you need them. If the lists came from delimited strings, stay with strings and use Series.str.split(sep, expand=True) or Series.str.get_dummies(sep=...) instead of creating lists first.
import pandas as pd
frame = pd.DataFrame({"k": ["a", "b"], "v": [[1, 2], [3]]})
try:
frame.drop_duplicates()
except TypeError as exc:
print("TypeError:", exc)
long = frame.explode("v").infer_objects()
print(long)
print(long["v"].dtype)
print(long.groupby("k", sort=False)["v"].agg(list))
Output:
TypeError: unhashable type: 'list' k v 0 a 1 0 a 2 1 b 3 int64 k a [1, 2] b [3] Name: v, dtype: object
Reading, merging and grouping surprises
-
Leading zeros disappear.
read_csvinfers numeric types, so identifiers such as007become integers. Declare identifier columns withdtype={"id": "str"}, and list sentinel strings inna_valuesso that a column withxin it is not silently parsed as text. -
Many-to-many merges multiply rows. When the key repeats on both sides every left row pairs with every right row. Pass
validate="one_to_one","one_to_many"or"many_to_one"to make pandas check and raiseMergeError, and useindicator=Trueto audit unmatched rows. -
groupbydrops missing keys. Rows whose key is missing disappear from the result unless you passdropna=False. -
Row-by-row loops are slow and change dtypes.
iterrows()builds a Series per row, so mixed columns are upcast toobject;itertuples()keeps types and is faster. Better still, use vectorised column expressions,maporgroupby. -
Assign results back. Inside a loop over columns, write
df[col] = df[col] * 2; mutating a temporary object has no effect under Copy-on-Write.
import io
import pandas as pd
csv = "id,qty\n007,1\n010,x\n"
raw = pd.read_csv(io.StringIO(csv))
print(raw["id"].tolist(), raw["qty"].tolist()) # ids lost their zeros
typed = pd.read_csv(io.StringIO(csv), dtype={"id": "str"}, na_values=["x"])
print(typed["id"].tolist(), typed["qty"].tolist(), typed["qty"].dtype)
left = pd.DataFrame({"k": [1, 1], "x": [1, 2]})
right = pd.DataFrame({"k": [1, 1], "y": [3, 4]})
print(len(left.merge(right, on="k"))) # 2 x 2 rows
try:
left.merge(right, on="k", validate="one_to_one")
except pd.errors.MergeError as exc:
print("MergeError:", str(exc).splitlines()[0])
g = pd.DataFrame({"k": ["a", None, "a"], "v": [1, 2, 3]})
print(g.groupby("k")["v"].sum().to_dict())
print(g.groupby("k", dropna=False)["v"].sum().to_dict())
Output:
[7, 10] ['1', 'x']
['007', '010'] [1.0, nan] float64
4
MergeError: Merge keys are not unique in either left or right dataset; not a one-to-one merge.
{'a': 4}
{'a': 4, nan: 2}
Source: pandas user guide: IO tools, Merge, join, concatenate and compare and Group by: split-apply-combine.
import numpy as np
import pandas as pd
it = pd.DataFrame({"i": [1, 2], "f": [1.5, 2.5], "s": ["x", "y"]})
for _, row in it.iterrows():
print(row.tolist(), row.dtype) # every value upcast to object
break
for t in it.itertuples(index=False):
print(t)
break
a = pd.DataFrame({"a": [1, 2, 3]})
for col in a.columns:
a[col] = a[col] * 2 # assign the result; do not mutate a copy
print(a["a"].tolist())
print(0.1 + 0.2 == 0.3, np.isclose(0.1 + 0.2, 0.3))
Output:
[1, 1.5, 'x'] object Pandas(i=1, f=1.5, s='x') [2, 4, 6] False True
Source: pandas reference: DataFrame.iterrows and DataFrame.itertuples.
See CSV and Text Files, Merge and Join and Group By.
Pandas 3 surprises
These are the changes that most often break working code. The migration page has the complete list; each point here has a short, runnable illustration.
-
Strings are not
objectany more.ser.dtype == objectisFalsefor text; usepd.api.types.is_string_dtype. Missing strings areNaN, andastype(str)keeps them missing instead of turning them into the textnan. Assigning a non-string value into astrSeries raisesTypeError. The separate"string"dtype (withpd.NA) still exists. -
Assigning an incompatible value raises. Writing
1.5into an integer column no longer silently converts the column to float; cast first withastype("float64"). -
Datetimes default to microsecond resolution.
astype("int64")on a datetime column returns values 1000 times smaller than code written for nanoseconds expects. Calldt.as_unit("ns")first if you need nanoseconds, or avoid integer casts and useTimestampandTimedeltaarithmetic. -
Chained assignment does nothing. See Copy-on-Write.
import numpy as np
import pandas as pd
words = pd.Series(["a", "b", None])
print(words.dtype, words.dtype == object, pd.api.types.is_string_dtype(words))
print(words.isna().tolist(), words.astype(str).tolist())
try:
words[1] = 2.5
except TypeError as exc:
print("TypeError:", str(exc).splitlines()[0][:60])
counts = pd.DataFrame({"n": [1, 2, 3]})
try:
counts.loc[0, "n"] = 1.5 # upcasting on assignment is refused
except TypeError as exc:
print("TypeError:", exc)
counts["n"] = counts["n"].astype("float64")
counts.loc[0, "n"] = 1.5
print(counts["n"].tolist())
stamps = pd.Series(pd.to_datetime(["2024-01-01 10:00"]))
print(stamps.dtype, stamps.astype("int64").tolist())
print(stamps.dt.as_unit("ns").dtype, stamps.dt.as_unit("ns").astype("int64").tolist())
Output:
str False True [False, False, True] ['a', 'b', nan] TypeError: Invalid value '2.5' for dtype 'str'. Value should be a strin TypeError: Invalid value '1.5' for dtype 'int64' [1.5, 2.0, 3.0] datetime64[us] [1704103200000000] datetime64[ns] [1704103200000000000]
Threads, byte order and other small print
-
Thread safety. pandas is not fully thread-safe; known problems involve
DataFrame.copy(). When several threads copy the same shared frame, serialise the copying with a lock. Process-based parallelism avoids the question. -
Byte order. Data created on a machine with the opposite byte order can fail with
Big-endian buffer not supported on little-endian compiler. Convert to the native order before building the object, for examplearr.byteswap().view(arr.dtype.newbyteorder()). -
Passing pandas objects to NumPy.
np.asarray(df)may return a read-only view (see Copy-on-Write); copy it before writing.