How to retrieve column names that has max and min value Zero and drop it the drop from the dataframe?

Viewed 23

Let assume we dataframe with data with name df: -

   Name     Scores     Project_score    Attendence
1  Kahn      25             0               0
2  Uri       22             0               0
3  John      24             0               0
4  Shushi    21             0               0
5  Johnny    25             0               0

I want to drop the columns that has max and min value equal to zero from the data. Note:- This is just a example data, there are more 100 columns in the data so we cannot all columns by selecting one by one using the code below

df.drop(['Attendence','Project_score'])

I need a loop statement or any function that can atleast retrieve me the names of the columns that has min and max value qual to zero.

1 Answers

Max and min value being equal to zero means a column is full of zero, and you need to find columns that have a value different than zero.

A more general solution for cases of mislabeled dtypes or float values would be to convert the applicable columns, whether it is string or float, to int dtype. However, for the cases like '0.0', we first need to convert the compatible columns to floats and then floats to ints so that the below solution will be applicable:

df = df.astype(float, errors='ignore').astype(int, errors='ignore')
df[df.columns[(df != 0).any()]]
Related