search
Search
Unlock 100+ guides
search toc
close
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
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

# Removing columns with some missing values in Pandas DataFrame

schedule Aug 11, 2023
Last updated
local_offer
PythonPandas
Tags
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

Consider the following DataFrame:

``` import numpy as npdf = pd.DataFrame({"A":["a",np.nan,np.nan,np.nan],"B":[3,5,np.nan,np.nan],"C":[6,7,8,np.nan]})df A B C0 a 3.0 6.01 NaN 5.0 7.02 NaN NaN 8.03 NaN NaN NaN ```

# Based on fixed number of non-missing values

To remove columns that has at least 2 non-missing values:

``` df.dropna(thresh=2, axis=1) B C0 3.0 6.01 5.0 7.02 NaN 8.03 NaN NaN ```

Here, column `A` is removed because this column contained only one non-missing value.

# Based on fixed number of missing values

To remove columns that has at least 2 missing values:

``` num_missing_values = 2df.dropna(thresh=len(df)-num_missing_values, axis=1) B C0 3.0 6.01 5.0 7.02 NaN 8.03 NaN NaN ```

Here, `len(df)` returns the number of rows of the DataFrame (`4` in this case). The thresh parameter is used to indicate the number of non-missing values that a row/column must at least have for it to be kept. This is the reason why we must subtract the number of missing values from the the total number of rows to get the total number of non-missing value.

# Based on proportions of non-missing values

To remove columns where half of its values are not missing:

``` df.dropna(thresh=len(df)*0.50, axis=1) B C0 3.0 6.01 5.0 7.02 NaN 8.03 NaN NaN ```

Note that `len(df)` returns the number of rows of the DataFrame (`4` in this case).

# Based on proportions of missing values

To remove columns where 70% of the values are missing:

``` prop_missing_value = 0.70df.dropna(thresh=(1-prop_missing_value) * len(df), axis=1) B C0 3.0 6.01 5.0 7.02 NaN 8.03 NaN NaN ```
Edited by 0 others
thumb_up
thumb_down
Comment
Citation
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!