delete row if it contain nan from dataframe in python

To delete rows from a Pandas DataFrame that contain NaN values, you can use the dropna() function.

Here's an example of how you can do this:

main.py
import pandas as pd

# Create a sample DataFrame
data = {'A': [1, 2, 3, None],
        'B': [4, None, 6, 7],
        'C': [8, 9, 10, 11]}
df = pd.DataFrame(data)

# Drop rows containing NaN values
df.dropna(inplace=True)

print(df)
232 chars
13 lines

This will remove any row that contains at least one NaN value from the DataFrame, and the resulting DataFrame will only contain rows with complete data.

Note that the inplace=True parameter is used to modify the DataFrame in place, meaning the original DataFrame will be changed. If you don't want to modify the original DataFrame, you can assign the result to a new variable:

main.py
df_cleaned = df.dropna()
25 chars
2 lines

Hope this helps!

related categories

gistlibby LogSnag