Articles → Pandas → Dropna Function In Pandas

Dropna Function In Pandas






Purpose





Example


import numpy as np
import pandas as pd

# Create a list
list = [[1,2,3], [4,5,6], [7, np.nan, np.nan]]

df = pd.DataFrame(list)

print("Initial\n", df)

df = df.dropna()

print("\nAfter dropping rows\n", df)




Picture showing the output of the dropna function in pandas
Click to Enlarge




Dropping Columns Using Dropna




  1. If value of axis = 0 it means dropna will drop rows. This is the default value.
  2. If value of axis = 1 it means dropna will drop columns
import numpy as np
import pandas as pd

# Create a list
list = [[1,2,3], [4,5,6], [7, np.nan, np.nan]]

df = pd.DataFrame(list)

print("Initial\n", df)

df = df.dropna(axis=1)

print("\nAfter dropping columns\n", df)




Picture showing dropping of columns in dropna function in pandas
Click to Enlarge


Thresh Attribute




import numpy as np
import pandas as pd

# Create a list
list = [[1,2,3], [4,np.nan,6], [7, np.nan, np.nan]]

df = pd.DataFrame(list)

print("Initial\n", df)

df = df.dropna(thresh=2)

print("\nAfter dropping rows\n", df)




  1. We are dropping rows using dropna function.
  2. We have mentioned the value of thresh=2. It means if there are 2 or more than 2 nan in a row then delete it.


Picture showing the output of Thresh attribute in dropna function in pandas
Click to Enlarge




Posted By  -  Karan Gupta
 
Posted On  -  Tuesday, April 30, 2019

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250