检查字符串是否在pandas datafram中

2024-04-27 22:10:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想看看在我的数据帧中的特定列中是否存在特定的字符串。

我明白了

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or 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"

Tags: ofthe数据字符串namesisvalueuse
3条回答

看来OP的意思是找出字符串Mel是否存在于特定列中,而不是列中包含的,因此不需要使用contains,也不是有效的。简单的等于就足够了:

(a['Names']=='Mel').any()

a['Names'].str.contains('Mel')将返回大小为len(BabyDataSet)的布尔值的指示向量

因此,您可以使用

mel_count=a['Names'].str.contains('Mel').sum()
if mel_count>0:
    print ("There are {m} Mels".format(m=mel_count))

或者any(),如果您不关心有多少记录与您的查询匹配

if a['Names'].str.contains('Mel').any():
    print ("Mel is there")

你应该使用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')提供一系列bool值

In [100]: a['Names'].str.contains('Mel')
Out[100]:
0    False
1    False
2    False
3    False
4     True
Name: Names, dtype: bool

相关问题 更多 >