如何确定 Pandas 列是否包含特定值 [英] How to determine whether a Pandas Column contains a particular value

查看:53
本文介绍了如何确定 Pandas 列是否包含特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定 Pandas 列中是否有具有特定值的条目.我试图用 if x in df['id'] 来做到这一点.我认为这是有效的,除了当我向它提供一个我知道不在 df['id'] 列 43 中的值时,它仍然返回 True.当我将数据框子集化为仅包含与缺少的 id df[df['id'] == 43] 匹配的条目时,显然其中没有条目.如何确定 Pandas 数据框中的列是否包含特定值,为什么我当前的方法不起作用?(仅供参考,当我在此回答类似问题中使用实现时,我遇到了同样的问题.

I am trying to determine whether there is an entry in a Pandas column that has a particular value. I tried to do this with if x in df['id']. I thought this was working, except when I fed it a value that I knew was not in the column 43 in df['id'] it still returned True. When I subset to a data frame only containing entries matching the missing id df[df['id'] == 43] there are, obviously, no entries in it. How to I determine if a column in a Pandas data frame contains a particular value and why doesn't my current method work? (FYI, I have the same problem when I use the implementation in this answer to a similar question).

推荐答案

in of a Series 检查值是否在索引中:

in of a Series checks whether the value is in the index:

In [11]: s = pd.Series(list('abc'))

In [12]: s
Out[12]: 
0    a
1    b
2    c
dtype: object

In [13]: 1 in s
Out[13]: True

In [14]: 'a' in s
Out[14]: False

一种选择是查看它是否在 unique 值中:

One option is to see if it's in unique values:

In [21]: s.unique()
Out[21]: array(['a', 'b', 'c'], dtype=object)

In [22]: 'a' in s.unique()
Out[22]: True

或一个 python 集:

or a python set:

In [23]: set(s)
Out[23]: {'a', 'b', 'c'}

In [24]: 'a' in set(s)
Out[24]: True

正如@DSM 所指出的,直接在值上使用 in 可能更有效(特别是如果您只是为一个值执行此操作):

As pointed out by @DSM, it may be more efficient (especially if you're just doing this for one value) to just use in directly on the values:

In [31]: s.values
Out[31]: array(['a', 'b', 'c'], dtype=object)

In [32]: 'a' in s.values
Out[32]: True

这篇关于如何确定 Pandas 列是否包含特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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