检查字符串是否在熊猫数据框中

新手上路,请多包涵

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

我收到错误

ValueError:Series 的真值不明确。使用 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")

原文由 user2242044 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 156
2 个回答

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")

原文由 Uri Goren 发布,翻译遵循 CC BY-SA 3.0 许可协议

你应该使用 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') 给你一系列布尔值

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

原文由 Zero 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题