How To Drop Rows Of Pandas DataFrame Whose Value In A Certain Column Is NaN

To drop rows with NaN values in a specific column of a Pandas DataFrame, you can use the dropna() method with the subset parameter. Here’s an example:

import pandas as pd

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

print("Original DataFrame:")
print(df)

# Drop rows with NaN values in column 'B'
df = df.dropna(subset=['B'])

print("\nUpdated DataFrame:")
print(df)

Output:

Original DataFrame:
     A    B     C
0  1.0  4.0   NaN
1  2.0  NaN   9.0
2  3.0  6.0  10.0
3  NaN  7.0  11.0

Updated DataFrame:
     A    B     C
0  1.0  4.0   NaN
2  3.0  6.0  10.0
3  NaN  7.0  11.0

In the example above, the rows containing NaN values in the ‘B’ column are dropped from the DataFrame. The resulting DataFrame is stored back in df.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!