How to Drop Null or N/A values in PandasYou can drop null values in a pandas DataFrame using the dropna() method.
Here's how you can do it:
import pandas as pd
# Create a sample DataFrame with null values
data = {'A': [1, 2, None, 4],
'B': [None, 5, 6, 7],
'C': [8, 9, 10, 11]}
df = pd.DataFrame(data)
# Drop rows with any null values
df.dropna(axis=0, inplace=True)
# Drop columns with any null values
df.dropna(axis=1, inplace=True)
# Drop rows with all null values
df.dropna(axis=0, how='all', inplace=True)
# Drop columns with all null values
df.dropna(axis=1, how='all', inplace=True)
In the above example, the dropna() method is used to drop rows or columns with null values from the DataFrame df. The axis parameter specifies whether to drop rows or columns (0 for rows, 1 for columns). The how parameter can be used to specify whether to drop rows or columns with all null values.
You can also drop null values from specific columns in a pandas DataFrame by specifying the subset parameter in the dropna() method.
Here's an example:
import pandas as pd
# Create a sample DataFrame with null values
data = {'A': [1, 2, None, 4],
'B': [None, 5, 6, 7],
'C': [8, 9, 10, 11]}
df = pd.DataFrame(data)
# Drop null values from specific columns
df.dropna(subset=['A', 'B'], inplace=True)
In the above example, the subset parameter is used to specify the columns from which null values should be dropped (in this case, columns 'A' and 'B'). Only rows with null values in columns 'A' or 'B' will be dropped from the DataFrame df.
#pandas
@real_python