Python 检查字符串是否在熊猫数据框中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30944577/
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
Check if string is in a pandas dataframe
提问by user2242044
I would like to see if a particular string exists in a particular column within my dataframe.
我想查看特定字符串是否存在于我的数据框中的特定列中。
I'm getting the error
我收到错误
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
ValueError:系列的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
import pandas as pd
BabyDataSet = [('Bob', 968), ('Jessica', 155), ('Mary', 77), ('John', 578), ('Mel', 973)]
a = pd.DataFrame(data=BabyDataSet, columns=['Names', 'Births'])
if a['Names'].str.contains('Mel'):
print "Mel is there"
采纳答案by Uri Goren
a['Names'].str.contains('Mel')
will return an indicator vector of boolean values of size len(BabyDataSet)
a['Names'].str.contains('Mel')
将返回大小为布尔值的指示向量 len(BabyDataSet)
Therefore, you can use
因此,您可以使用
mel_count=a['Names'].str.contains('Mel').sum()
if mel_count>0:
print ("There are {m} Mels".format(m=mel_count))
Or any()
, if you don't care how many records match your query
或者any()
,如果您不关心有多少记录匹配您的查询
if a['Names'].str.contains('Mel').any():
print ("Mel is there")
回答by Zero
You should use any()
你应该使用 any()
In [98]: a['Names'].str.contains('Mel').any()
Out[98]: True
In [99]: if a['Names'].str.contains('Mel').any():
....: print "Mel is there"
....:
Mel is there
a['Names'].str.contains('Mel')
gives you a series of bool values
a['Names'].str.contains('Mel')
给你一系列布尔值
In [100]: a['Names'].str.contains('Mel')
Out[100]:
0 False
1 False
2 False
3 False
4 True
Name: Names, dtype: bool
回答by Shahir Ansari
You should check the value of your line of code like adding checking length of it.
您应该检查代码行的值,例如添加检查长度。
if(len(a['Names'].str.contains('Mel'))>0):
print("Name Present")
回答by meizy
it seems that the OP meant to find out whether the string 'Mel' existsin a particular column, not containedin a column, therefore the use of containsis not needed, and is not efficient. A simple equals-to is enough:
似乎 OP 旨在找出字符串 'Mel' 是否存在于特定列中,而不包含在列中,因此不需要使用contains,并且效率不高。一个简单的等于就足够了:
(a['Names']=='Mel').any()
回答by Christian
I bumped into the same problem, I used:
我遇到了同样的问题,我用过:
if "Mel" in a["Names"].values:
print("Yep")
But this solution may be slower since internally pandas create a list from a Series.
但是这个解决方案可能会更慢,因为熊猫在内部创建了一个系列的列表。