简体   繁体   中英

Drop all rows in Pandas DataFrame where value is NOT NaN

I can remove all rows with nan in a column with this line:

df2 = df.dropna(subset=['columnA'])

How do I remove all rows that have values other than NaN?

You can do drop

df2 = df.dropna(subset=['columnA'])
df1 = df.drop(df2.index)
df.loc[lambda x:x.columnA.isnull()]

I might be missing something in the question.

Just keep the rows where value is equal to np.nan

As @rafaelc pointed out np.nan == np.nan is false .

And I was completely wrong I am leaving the answer here just to keep the comments here for anyone who comes looking.

Changing based on that.

df2 = df[df['ColumnA'] != np.nan]   # WRONG ANSWER
df1 = df[~(df['ColumnA'] != np.nan)] #WRONG ANSWER

# perform function on df1  # WRONG ANSWER

df_f = pd.concat([df1,df2])

另一种解决方案:

 df2 = df.loc[df['columnA'].isnull()]

我认为这是最合乎逻辑和最简单的解决方案:

df = df[df['columnA'].isnull()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM