How to drop missing values in pandas?
Published on Aug. 22, 2023, 12:18 p.m.
To drop missing values in pandas, you can use the dropna()
method on a pandas DataFrame. By default, dropna()
removes all rows that contain any missing values. Here is an example:
import pandas as pd
# create a sample dataframe with missing values
df = pd.DataFrame({'A': [1, 2, None, 4], 'B': [5, 6, 7, None]})
# drop all rows with missing values
df = df.dropna()
print(df)
This will output a new DataFrame with all rows containing missing values removed:
A B
0 1 5
1 2 6
If you want to remove columns with missing values instead of rows, you can set the axis
parameter to 1:
df = df.dropna(axis=1)
This will remove all columns containing missing values.