首页 > 解决方案 > 如何在 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 

标签: pythonpandasdataframe

解决方案


你不能and在 pandas 掩码操作中使用关键字,你需要&像这样使用按位运算符:

assert any(result_df.loc[result_df['colA'].str.contains('A_val') & result_df['colB'].str.contains('B_val')]['colC'] == 'C_val')

推荐阅读