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)
Click to Enlarge
Dropping Columns Using Dropna
- If value of axis = 0 it means dropna will drop rows. This is the default value.
- 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)
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)
- We are dropping rows using dropna function.
- 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.
Click to Enlarge