pandas 删除熊猫列中的负值保留 NaN

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44133219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:40:36  来源:igfitidea点击:

Removing negative values in pandas column keeping NaN

python-3.xpandas

提问by Jennifer Drake

I was wondering how I can remove rows which have a negative value but keep the NaNs. At the moment I am using:

我想知道如何删除具有负值但保留 NaN 的行。目前我正在使用:

DF = DF.ix[DF['RAF01Time'] >= 0]

But this removes the NaNs.

但这会删除 NaN。

Thanks in advance.

提前致谢。

采纳答案by jezrael

You need boolean indexingwith another condition with isnull:

你需要boolean indexing另一个条件isnull

DF = DF[(DF['RAF01Time'] >= 0) | (DF['RAF01Time'].isnull())]

Sample:

样本:

DF = pd.DataFrame({'RAF01Time':[-1,2,3,np.nan]})
print (DF)
   RAF01Time
0       -1.0
1        2.0
2        3.0
3        NaN

DF = DF[(DF['RAF01Time'] >= 0) | (DF['RAF01Time'].isnull())]
print (DF)
   RAF01Time
1        2.0
2        3.0
3        NaN

Another solution with query:

另一个解决方案query

DF = DF.query("~(RAF01Time < 0)")
print (DF)
   RAF01Time
1        2.0
2        3.0
3        NaN

回答by Allen

You can just use < 0and then take the inverse of the condition.

您可以只使用< 0然后取条件的倒数。

DF = DF[~(DF['RAF01Time'] < 0)]