Answers, not search results
258 worked answers to the questions data analysts actually ask. Every one written from scratch, with runnable code. Describe your problem in your own words, or filter by stack.
-
Python Intermediate
Why does a mutable default argument cause bugs in Python?
A default argument is created once when the function is defined, not on each call, so a mutable default like a list is shared across calls and accumulates changes. Use None as the default and build the object inside.
Read the answer -
Python Advanced
Why does astype to a smaller integer type give the wrong number in NumPy?
astype does not check the range, so a value too large for the target type wraps around silently. Check the range before downcasting, or use pandas to_numeric with downcast which picks a safe type.
Read the answer -
Python Advanced
Why does changing a NumPy slice also change the original array?
A basic slice of a NumPy array is a view that shares memory with the original, so writing to it changes both. Use .copy() when you need an independent array, and note that fancy indexing already returns a copy.
Read the answer -
Python Advanced
Why does comparing with pd.NA give NA instead of True or False?
pd.NA propagates through comparisons because the result of comparing an unknown value is itself unknown. Use isna to test for missing values, never an equality comparison.
Read the answer -
Python Intermediate
Why does groupby change the order of my results in pandas?
groupby sorts the group keys by default, so the output order is alphabetical rather than the order the groups appeared. Pass sort=False to keep first-appearance order, which is also slightly faster.
Read the answer -
Python Advanced
Why does groupby drop rows with missing keys in pandas?
By default groupby excludes rows whose grouping key is NaN, so those rows vanish from the result and totals silently under-count. Pass dropna=False to keep them as their own group.
Read the answer -
Python Advanced
Why does groupby on a categorical column produce empty groups in pandas?
Grouping a categorical column includes every defined category by default, even ones with no rows, which pads the result with empty groups. Pass observed=True to include only the categories that actually appear.
Read the answer -
Python Advanced
Why does loc return several rows for a single label in pandas?
A duplicated index label matches every row that carries it, so loc returns a frame rather than a row. Check the index is unique before relying on label lookups.
Read the answer -
Python Intermediate
Why does mean return nan in NumPy, and how do I ignore missing values?
Any nan in an array poisons a normal mean or sum, because nan propagates through arithmetic. Use the nan-aware functions like nanmean and nansum to skip missing values instead.
Read the answer -
Python Advanced
Why does my Jupyter notebook give different results when I re-run it?
A notebook keeps hidden state from every cell you have run, in whatever order you ran them, so the visible code may not be what produced the output. Restart and run all before trusting a result.
Read the answer -
Python Intermediate
Why does my merge produce more rows than either input?
Because the join key is not unique on at least one side, so pandas produces every matching combination. Check for duplicate keys before you merge, not after.
Read the answer -
Python Advanced
Why does my missing-value check miss some rows in pandas?
isna only finds NaN and None, not empty strings, whitespace or placeholder text like NA or minus one. Convert those to real missing values first, or your checks and fills will silently skip them.
Read the answer -
Python Advanced
Why does my NumPy integer calculation give a wrong or negative result?
NumPy integers have a fixed size, so a value that exceeds the type's range wraps around silently, sometimes to a negative number. Choose a wider dtype, or convert to float, when values can grow large.
Read the answer -
Python Advanced
Why does my pandas script use so much more memory than the file size?
A CSV expands in memory because text becomes Python objects and numbers default to 64 bit, and every intermediate frame is held until it is released. Read with narrow dtypes and avoid keeping copies you no longer need.
Read the answer -
Python Beginner
Why does my saved CSV have an extra unnamed column?
to_csv writes the DataFrame index as a column by default, which reappears as Unnamed 0 when you read the file back. Pass index=False when saving, or index_col=0 when reading.
Read the answer -
Python Advanced
Why does pivot raise a duplicate entries error in pandas?
pivot cannot aggregate, so two rows sharing the same index and column combination have no single value to place in the cell and it raises. Use pivot_table, which aggregates, or deduplicate first.
Read the answer -
Python Advanced
Why does qcut fail with a bin edges must be unique error?
qcut computes bin edges from quantiles, so a column with many repeated values produces duplicate edges and raises. Pass duplicates="drop" to merge them, accepting that you get fewer bins than you asked for.
Read the answer -
Python Intermediate
Why does removing items from a list while looping over it skip elements?
Removing an item shifts everything after it back by one, but the loop's counter keeps advancing, so the next item is skipped. Build a new list with a comprehension instead of mutating while iterating.
Read the answer -
Python Advanced
Why does resample show zeros for periods with no data?
Summing an empty period gives zero, which is indistinguishable from a real zero, so gaps in your data look like genuine lows. Use asfreq or a count to tell the difference between no data and no activity.
Read the answer -
Python Advanced
Why does round(0.5) give 0 in Python?
Python rounds halves to the nearest even number, so round(0.5) is 0 and round(2.5) is 2. Float imprecision adds a second surprise, making round(2.675, 2) give 2.67 rather than 2.68.
Read the answer -
Python Advanced
Why does selecting one column return a DataFrame instead of a Series?
If two columns share a name, selecting that name returns both as a DataFrame, so anything expecting a Series breaks. Rename or drop the duplicate, and check for repeated names after a merge.
Read the answer -
Python Advanced
Why does sum return zero but mean return NaN on an empty column?
Summing nothing gives zero by mathematical convention, while averaging nothing is undefined and gives NaN. This inconsistency means an empty filter can silently produce a confident zero in a report.
Read the answer -
Python Intermediate
Why do I get columns ending in _x and _y after a merge in pandas?
When both frames have a column with the same name that is not a join key, merge keeps both and disambiguates them with _x and _y. Rename with the suffixes argument, or drop the column you do not need.
Read the answer -
Python Advanced
Why do I get NaN when adding two pandas Series together?
Pandas aligns on the index before doing arithmetic, so labels present in one Series but not the other produce NaN. Reset the index, or use values, when you mean to combine by position.
Read the answer -
Python Advanced
Why is adding a day to a datetime wrong across a daylight saving change?
Adding a timedelta to an aware datetime keeps the wall clock time, so across a clock change only 23 or 25 hours actually pass. Convert to UTC, add the duration, then convert back if you mean a true elapsed day.
Read the answer