In pandas, how do DataFrame.dropna's how, thresh, subset and axis arguments decide which rows or columns are removed?
answer
- any by default, or all
- thresh counts present values
- subset narrows the columns checked
- how and thresh do not mix
- axis='columns' drops columns instead
basics
~20 sdropna removes rows by default when any cell is missing. how='all' drops only fully empty rows, thresh=n keeps rows with at least n non-missing values, subset limits which columns are checked, and axis='columns' drops columns instead.
solid answer
~30 sWith its defaults, `axis=0` and `how='any'`, `dropna()` removes every row that has at least one missing cell. `how='all'` removes only rows where every checked cell is missing. `thresh=n` keeps rows that have **at least n non-missing** values, a count of present values, not of gaps. `subset` restricts which columns are inspected, so `dropna(subset=['temp_c', 'humidity'], how='all')` drops readings rows with no measurement while ignoring the ID columns. `how` and `thresh` cannot be passed together; pandas raises `TypeError`. `axis='columns'` applies the same rules to columns, and then `subset` lists row labels. The result keeps the original index labels unless `ignore_index=True`.
code
python · 18 linesimport numpy as np
import pandas as pd
log = pd.DataFrame(
{
"device": ["d1", "d2", "d3", "d4"],
"temp_c": [21.0, np.nan, np.nan, 19.5],
"humidity": [40.0, 42.0, np.nan, np.nan],
"notes": [np.nan, np.nan, np.nan, np.nan],
}
)
readings = ["temp_c", "humidity"]
print(log.dropna().shape) # notes is empty, so every row goes
print(log.dropna(axis="columns", how="all").columns.tolist())
print(log.dropna(subset=readings, how="all").index.tolist())
print(log.dropna(subset=readings, thresh=2).index.tolist())
print(log.dropna(subset=readings).index.tolist())go deeper
Recall that dropna drops rows with any gap by default and that how='all' only drops rows with nothing in them.
Explain that thresh counts present values, that subset decides which columns take part, and that how and thresh cannot be combined.
Diagnose a cleaning step that returned an empty frame because of one blank column, and drop empty columns before dropping rows.
Insist that every dropna in shared pipeline code names its subset explicitly, so a new sparse column added upstream cannot silently delete rows.
## The signature and its defaults `DataFrame.dropna` takes only keyword arguments: `axis` (default `0`), `how` (behaves as `'any'` when not given), `thresh` (unset by default), `subset=None`, `inplace=False` and `ignore_index=False`. Each argument answers one question about what to remove: - **`axis`**: remove **rows** (`0` or `'index'`, the default) or **columns** (`1` or `'columns'`). - **`how`**: remove a row when **any** checked cell is missing (`'any'`, the default) or only when **all** of them are (`'all'`). - **`thresh`**: keep a row only if it has **at least this many non-missing values**. - **`subset`**: which labels along the other axis to check, usually a list of column names. - **`ignore_index`**: relabel the result 0 to n-1 instead of keeping the original labels. ## how='any' versus how='all' The default `how='any'` is strict: one missing cell anywhere in a row removes the whole row, including all of its present values. That strictness is easy to underestimate. If a frame carries a free-text `notes` column that is empty everywhere, `df.dropna()` returns **zero rows**, because every row has a gap in `notes`. `how='all'` removes only rows in which **every** checked cell is missing, which is the right tool for rows that carry no information, such as blank lines from a spreadsheet export. ## thresh: a count of present values `thresh=n` is the argument most often misremembered. The docstring says it requires that many **non-NA** values. So on a frame with five columns: - `thresh=4` keeps rows with at least four present values, meaning at most one gap. - `thresh=1` keeps every row that has at least one present value, the same rows as `how='all'`. - It is **not** "drop rows with more than n gaps"; reading it that way inverts the filter. `how` and `thresh` express overlapping rules, so pandas refuses both at once: `df.dropna(how='all', thresh=2)` raises `TypeError` ("You cannot set both the how and thresh arguments at the same time"). ## subset: deciding which columns count Without `subset`, every column takes part in the test, including IDs, timestamps and labels that are never missing. That skews `thresh`, because the always-present columns count towards the threshold. Typical IoT patterns: 1. `df.dropna(subset=['temp_c', 'humidity'], how='all')` drops rows where the sensor reported no measurement at all, whatever the ID columns hold. 2. `df.dropna(subset=['temp_c', 'humidity'], thresh=2)` keeps only rows where both measurements are present. 3. `df.dropna(subset='temp_c')` accepts a single label too; pandas wraps it in a list. A label in `subset` that does not exist raises `KeyError`, which catches a typo in a column name rather than silently checking nothing. ## axis='columns': dropping columns With `axis='columns'` the same rules apply to columns. `df.dropna(axis='columns', how='all')` removes columns that are entirely empty, such as a decommissioned sensor's channel, and is often the step to run **before** a row-wise `dropna()` so that an empty column does not wipe out every row. With `axis='columns'`, `subset` names **row labels**, the labels along the other axis. ## What the result looks like | Call | Rows kept | Columns kept | |---|---|---| | `df.dropna()` | rows with no gap in any column | all | | `df.dropna(how='all')` | rows with at least one present value | all | | `df.dropna(thresh=3)` | rows with at least 3 present values | all | | `df.dropna(subset=['temp_c'])` | rows where `temp_c` is present | all | | `df.dropna(axis='columns', how='all')` | all | columns with at least one present value | The result is a new DataFrame; the original index labels survive with holes where rows were removed, and `ignore_index=True` renumbers them. With `inplace=True`, `dropna` modifies the frame and returns `None`, so it cannot sit inside a method chain; assigning the result, as in `df = df.dropna(subset=['temp_c'])`, is the usual form. ## Series.dropna On a Series, `dropna()` simply removes the missing entries and returns a shorter Series; there are no columns, so `how`, `thresh` and `subset` do not apply. `df['temp_c'].dropna()` is therefore a quick way to work with only the valid readings of one column without removing rows from the frame itself. ## Before you drop Measure first: compare `len(df)` before and after, and look at `df.isna().sum()` to see which column drives the loss. Whether dropping is the right decision for the analysis at all is covered in the library-neutral material on missing values; this lesson is about what each argument removes.
- Why do dropna(subset=cols, thresh=len(cols)) and dropna(subset=cols) keep the same rows?Requiring as many present values as there are checked columns means no checked column may be missing, which is exactly the default `how='any'` rule over the same subset. The `thresh` form becomes useful only when the number is smaller than the subset, such as two of three readings.
- How do you drop rows where every measurement column is missing but keep the IDs in the decision out?Pass the measurement columns as `subset` with `how='all'`, for example `df.dropna(subset=['temp_c', 'humidity', 'battery'], how='all')`. ID and timestamp columns are then ignored by the test, so a row that has only its device ID and timestamp is removed.
- Reading thresh=2 as dropping rows with more than two missing values.
- Assuming the default dropna() only removes completely empty rows.
- Passing how and thresh together and expecting both to apply.
- Forgetting that ID columns count towards thresh without subset.
- Expecting dropna() to renumber the index without ignore_index=True.