Home >Backend Development >Python Tutorial >How to Filter a Pandas DataFrame to Keep Only Rows with Non-NaN Values in a Specific Column?

How to Filter a Pandas DataFrame to Keep Only Rows with Non-NaN Values in a Specific Column?

Linda Hamilton
Linda HamiltonOriginal
2024-12-14 17:52:16123browse

How to Filter a Pandas DataFrame to Keep Only Rows with Non-NaN Values in a Specific Column?

How to Isolate Non-NaN Values in a Column of a Pandas DataFrame

Question:

Consider a DataFrame like this:

STK_ID RPT_Date                   <br>601166 20111231  601166  NaN   NaN<br>600036 20111231  600036  NaN    12<br>600016 20111231  600016  4.3   NaN<br>601009 20111231  601009  NaN   NaN<br>601939 20111231  601939  2.5   NaN<br>000001 20111231  000001  NaN   NaN<br>

Goal:

Isolate the records where the "EPS" column is not NaN, resulting in this DataFrame:

STK_ID RPT_Date                   <br>600016 20111231  600016  4.3   NaN<br>601939 20111231  601939  2.5   NaN<br>

Solution:

Instead of dropping rows, you can filter the DataFrame using the notna() method to select only the rows where the "EPS" column is not NaN:

df = df[df['EPS'].notna()]

This will create a new DataFrame with the desired result.

The above is the detailed content of How to Filter a Pandas DataFrame to Keep Only Rows with Non-NaN Values in a Specific Column?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn