Python - Remove a column with all null values in Pandas

PythonServer Side ProgrammingProgramming

To remove a column with all null values, use the dropna() method and set the “how” parameter to “all” −

how='all'

At first, let us import the required libraries with their respective aliases −

import pandas as pd
import numpy as np

Create a DataFrame. We have set the NaN values using the Numpy np.inf

dataFrame = pd.DataFrame(
   {
      "Student": ['Jack', 'Robin', 'Ted', 'Robin', 'Scarlett', 'Kat', 'Ted'],"Result": [np.NAN, np.NAN, np.NAN, np.NAN, np.NAN, np.NAN,np.NAN]
   }
)

To remove a column with all null values, use dropna() and set the required parameters −

dataFrame.dropna(how='all', axis=1, inplace=True)

Example

Following is the code −

import numpy as np
import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Student": ['Jack', 'Robin', 'Ted', 'Robin', 'Scarlett', 'Kat', 'Ted'],"Result": [np.NAN, np.NAN, np.NAN, np.NAN, np.NAN, np.NAN,np.NAN]
   }
)

print"DataFrame ...\n",dataFrame

dataFrame.dropna(how='all', axis=1, inplace=True)
print"\nDataFrame ...\n",dataFrame

Output

This will produce the following output −

DataFrame ...
   Result   Student
0     NaN      Jack
1     NaN     Robin
2     NaN       Ted
3     NaN     Robin
4     NaN  Scarlett
5     NaN       Kat
6     NaN       Ted

DataFrame ...
   Student
0     Jack
1    Robin
2      Ted
3    Robin
4 Scarlett
5      Kat
6      Ted
raja
Published on 20-Sep-2021 12:45:19
Advertisements