In Pandas, you can filter out NaN (Not a Number) values from a DataFrame using the dropna() method or boolean indexing.
Here's how you can do it:
Using dropna() method:import pandas as pd
# Example DataFrame
df = pd.DataFrame({'A': [1, 2, None, 4],
'B': [5, None, 7, 8]})
# Drop rows containing NaN values
filtered_df = df.dropna()
print(filtered_df)
This will drop any row that contains at least one NaN value.
Using boolean indexing:
import pandas as pd
import numpy as np
# Example DataFrame
df = pd.DataFrame({'A': [1, 2, np.nan, 4],
'B': [5, np.nan, 7, 8]})
# Filter rows where NaN values are present in any column
filtered_df = df[~df.isnull().any(axis=1)]
print(filtered_df)
In this example, df.isnull().any(axis=1) returns a boolean Series indicating whether there are any NaN values in each row. Then, ~ is used to negate this Series, and it is used to filter out rows that contain any NaN values.
Both methods will result in a DataFrame with rows that do not contain any NaN values. Choose the method that best fits your workflow and preferences.