python - 如何在 Pandas Dataframe 中断言单元格值
问题描述
我正在编写 pytest 单元测试用例,其中调用返回一个 Pandas 数据框,我想在其中声明一个特定的单元格值。我试过这个但把我扔了E ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
assert result_df.loc[result_df['col_A'].str.contains('A_val') and result_df['col_B'].str.contains('2018-05-13'), 'col_C'].item() == 'Q3'
这是我的示例数据:
id col_A col_B
0 RK7 A_val 2018-05-13
1 RK7 A_val 2018-09-02
0 BM A1_val 2018-05-05
1 BM A1_val 2018-05-05
col_C
0 Q3
1 Q4
0 Q1
1 Q2
解决方案
你不能and
在 pandas 掩码操作中使用关键字,你需要&
像这样使用按位运算符:
assert any(result_df.loc[result_df['colA'].str.contains('A_val') & result_df['colB'].str.contains('B_val')]['colC'] == 'C_val')
推荐阅读
- c# - 增量运算符如何处理数组?
- c - 用C字符串中的转义字符双引号替换双引号
- python - 如何将火炬张量转换为熊猫数据框?
- javascript - 正则表达式只有 8 个字符长,但不超过 2 个数字
- python-3.x - Python:NSEpy 模块:无法获取期货实时数据
- powershell - 如何从提示和代码清理中重置 csv 中所有用户的密码
- kinect - 是否有主题或服务可以了解 RTAB-MAP 中何时丢失视觉里程计估计?
- php - Laravel 5.2 - 使用带有数组值的附加方法
- out-of-memory - 如何在 PyTorch 中节省 GPU 内存使用量
- php - CSV 文件输出 - 在开头插入一个附加列