search
Search
Guest 0reps
Thanks for the thanks!
close
account_circle
Profile
exit_to_app
Sign out
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
Doc Search
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Shrink
Navigate to
A
A
brightness_medium
share
arrow_backShare

# Getting integer indexes of rows with NaN in Pandas DataFrame

Pandas
chevron_right
Cookbooks
chevron_right
DataFrame Cookbooks
chevron_right
Handling Missing Values
schedule Jul 1, 2022
Last updated
local_offer PythonPandas
Tags
expand_more

# Rows with missing value for a specific column

Consider the following DataFrame with some missing values:

``` import numpy as npdf = pd.DataFrame({"A":[3,np.nan,np.nan],"B":[5,6,np.nan]}, index= ["a","b","c"])df A Ba 3.0 5.0b NaN 6.0c NaN NaN ```

## Solution

To get the integer indexes of rows where the value for column `A` is missing:

``` np.where(df["A"].isna())[0] # returns a NumPy array array([1, 2]) ```

## Explanation

We first call `isna()` to extract a Series of booleans where `True` indicates rows with missing value(s) for column `A`:

``` df["A"].isna() a Falseb Truec TrueName: A, dtype: bool ```

We then call NumPy's `where(~)`, which returns a tuple containing the integer indexes of entries that are `True`:

``` np.where(df["A"].isna()) (array([1, 2]),) ```

Finally, we use `[0]` to access the NumPy array of integer indexes within the tuple.

# Rows with all missing values

Consider the following DataFrame:

``` import numpy as npdf = pd.DataFrame({"A":[3,np.nan,np.nan],"B":[5,6,np.nan]}, index= ["a","b","c"])df A Ba 3.0 5.0b NaN 6.0c NaN NaN ```

## Solution

To get the integer indexes of rows with all missing values:

``` np.where(df.isna().all(axis=1))[0] # returns a NumPy array array([2]) ```

## Explanation

We first obtain a DataFrame of booleans where `True` represents entries with missing values using `isna()`:

``` df.isna() A Ba False Falseb True Falsec True True ```

We then call `all(axis=1)`, which returns a Series of booleans where `True` indicates a row with all `True`:

``` df.isna().all(axis=1) a Falseb Falsec Truedtype: bool ```

We pass this into NumPy's `where(~)` method, which returns a tuple containing the integer indexes of entries that are `True`:

``` np.where(df.isna().all(axis=1)) (array([2]),) ```

We then access the integer indexes, which is a NumPy array, using `[]` notation:

``` np.where(df.isna().all(axis=1))[0] array([2]) ```
mail
Edited by 0 others
thumb_up
thumb_down
Ask a question or leave a feedback...
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!