pandas 使用.isin()检查nan无法正常工作 [英] pandas checking for nan not working using .isin()

查看:103
本文介绍了 pandas 使用.isin()检查nan无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下带有NaN的熊猫数据框.

I have the following pandas Dataframe with a NaN in it.

import pandas as pd
df = pd.DataFrame([1,2,3,float('nan')], columns=['A'])
df

    A
0   1
1   2
2   3
3 NaN

我还有一个列表filter_list,我想使用该列表过滤我的数据框.但是,如果我使用.isin()功能,则不会检测到NaN.而不是得到True,我得到的是最后一行中的False

I also have the list filter_list using which I want to filter my Dataframe. But if i use .isin() function, it is not detecting the NaN. Instead of getting True I am getting False in the last row

filter_list = [1, float('nan')]

df['A'].isin(filter_list)
0     True
1    False
2    False
3    False
Name: A, dtype: bool

预期输出:

0     True
1    False
2    False
3    True
Name: A, dtype: bool

我知道我可以使用.isnull()检查NaNs.但是在这里,我还需要检查其他值.我正在使用熊猫0.16.0版本

I know that I can use .isnull() to check for NaNs. But here I have other values to check as well. I am using pandas 0.16.0 version

列表filter_list来自用户.因此,它可能有或没有NaN.那就是为什么我使用.isin()

The list filter_list comes from the user. So it might or might not have NaN. Thats why i am using .isin()

推荐答案

您可以将nan替换为列表中不会出现的唯一非NaN值,例如'NA'''.例如:

You could replace nan with a unique non-NaN value that will not occur in your list, say 'NA' or ''. For example:

In [23]: import pandas as pd

In [24]: df = pd.DataFrame([1, 2, 3, pd.np.nan], columns=['A'])

In [25]: filter_list = pd.Series([1, pd.np.nan])

In [26]: na_equiv = 'NA'

In [27]: df['A'].replace(pd.np.nan, na_equiv).isin(filter_list.replace(pd.np.nan, na_equiv))
Out[27]:
0     True
1    False
2    False
3     True
Name: A, dtype: bool

这篇关于 pandas 使用.isin()检查nan无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆