python - 如何断言根据条件过滤的熊猫数据框为真
问题描述
所以我有一个 pytest 测试返回熊猫数据框的查询结果。
我想断言特定列col
的所有值都是给定输入的子字符串。
因此,下面的内容为我提供了该列的col
值包含某些输入部分的行(数据框)。我怎样才能断言它是真实的?
assert result_df[result_df['col'].astype(str).str.contains(category)].bool == True
不工作
解决方案
我相信您需要Series.all
检查过滤的所有值是否Series
都是True
s:
assert result_df['col'].astype(str).str.contains(category).all()
样品:
result_df = pd.DataFrame({
'col':list('aaabbb')
})
print (result_df)
col
0 a
1 a
2 a
3 b
4 b
5 b
category = 'b'
assert result_df['col'].astype(str).str.contains(category).all()
断言错误
详情:
print (result_df['col'].astype(str).str.contains(category))
0 False
1 False
2 False
3 True
4 True
5 True
Name: col, dtype: bool
print (result_df['col'].astype(str).str.contains(category).all())
False
category = 'a|b'
assert result_df['col'].astype(str).str.contains(category).all()
print (result_df['col'].astype(str).str.contains(category))
0 True
1 True
2 True
3 True
4 True
5 True
Name: col, dtype: bool
print (result_df['col'].astype(str).str.contains(category).all())
True
推荐阅读
- python - 没有在哪里部署 Python Flask API 项目
- r - 绘制气泡图:单个轴上的所有路径项
- python - /profile/ 处的 AttributeError
- asynchronous - 异步 gunicorn 抛出 Cors 问题,但 Sync gunicorn 工作正常
- php - PHP Laravel save() 没有更新记录
- python - 如何在 django-models 中以特定/自定义的方式订购数据?
- android - 创建位图而不在 UI 上显示 - 小问题
- xml - xmlstarlet:删除具有特定属性值的标签及其子标签
- python-3.x - PIL 的 Image.rotate() 裁剪图像
- php - 如何在 WooCommerce 中查找任何国家/地区的州/城市