首页 > 解决方案 > 如何断言根据条件过滤的熊猫数据框为真

问题描述

所以我有一个 pytest 测试返回熊猫数据框的查询结果。

我想断言特定列col的所有值都是给定输入的子字符串。

因此,下面的内容为我提供了该列的col值包含某些输入部分的行(数据框)。我怎样才能断言它是真实的?

assert result_df[result_df['col'].astype(str).str.contains(category)].bool == True 

不工作

标签: pythonpandaspytest

解决方案


我相信您需要Series.all检查过滤的所有值是否Series都是Trues:

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

推荐阅读