Removing columns with some missing values in Pandas DataFrame
Start your free 7-days trial now!
Consider the following DataFrame:
import numpy as npdf
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:
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 = 2
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:
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.70
B C0 3.0 6.01 5.0 7.02 NaN 8.03 NaN NaN