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).
当前回答
你可以试着检查一个名为“id”的列中的特定值“x”
if x in df['id'].values
其他回答
你也可以使用pandas.Series.isin,尽管它比s.values中的'a'长一点:
In [2]: s = pd.Series(list('abc'))
In [3]: s
Out[3]:
0 a
1 b
2 c
dtype: object
In [3]: s.isin(['a'])
Out[3]:
0 True
1 False
2 False
dtype: bool
In [4]: s[s.isin(['a'])].empty
Out[4]: False
In [5]: s[s.isin(['z'])].empty
Out[5]: True
但是,如果您需要为一个DataFrame同时匹配多个值,这种方法可以更加灵活。
>>> df = DataFrame({'A': [1, 2, 3], 'B': [1, 4, 7]})
>>> df.isin({'A': [1, 3], 'B': [4, 7, 12]})
A B
0 True False # Note that B didn't match 1 here.
1 False True
2 True True
Series的in检查该值是否在索引中:
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
一种选择是查看它是否为唯一值:
In [21]: s.unique()
Out[21]: array(['a', 'b', 'c'], dtype=object)
In [22]: 'a' in s.unique()
Out[22]: True
或者一个python集合:
In [23]: set(s)
Out[23]: {'a', 'b', 'c'}
In [24]: 'a' in set(s)
Out[24]: True
正如@DSM所指出的,直接在值上使用in可能更有效(特别是如果你只对一个值执行此操作):
In [31]: s.values
Out[31]: array(['a', 'b', 'c'], dtype=object)
In [32]: 'a' in s.values
Out[32]: True
你可以试着检查一个名为“id”的列中的特定值“x”
if x in df['id'].values
我有一个CSV文件要读取:
df = pd.read_csv('50_states.csv')
在尝试之后:
if value in df.column:
print(True)
即使值在列中,它也不会输出true;
我试着:
for values in df.column:
if value == values:
print(True)
#Or do something
else:
print(False)
这工作。希望这能有所帮助!
假设你的数据框架是这样的:
现在你要检查文件名“80900026941984”是否存在于数据帧中。
你可以简单地写:
if sum(df["filename"].astype("str").str.contains("80900026941984")) > 0:
print("found")
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录