在第一种情况tdf.col2[0] == '2022Q1'
中,使用Python ==
运算符进行比较,当比较Period(pd.Period('2022Q1')
)to a string时,结果为False
(与2 == '2'
产生False
的方式相同).
在第二种情况tdf[tdf.col1 == 'a'].col2 == '2022Q1'
中,比较使用pandas比较操作的Series to a string,请参见以下调用堆栈:
...\lib\site-packages\pandas\core\ops\common.py(70)new_method()
-> return method(self, other)
...\lib\site-packages\pandas\core\arraylike.py(40)__eq__()
-> return self._cmp_method(other, operator.eq)
...\lib\site-packages\pandas\core\series.py(5623)_cmp_method()
-> res_values = ops.comparison_op(lvalues, rvalues, op)
...\lib\site-packages\pandas\core\ops\array_ops.py(269)comparison_op()
-> res_values = op(lvalues, rvalues)
...\lib\site-packages\pandas\core\ops\common.py(70)new_method()
-> return method(self, other)
...\lib\site-packages\pandas\core\arraylike.py(40)__eq__()
-> return self._cmp_method(other, operator.eq)
...\lib\site-packages\pandas\core\arrays\datetimelike.py(1008)_cmp_method()
-> other = self._validate_comparison_value(other)
...\lib\site-packages\pandas\core\arrays\datetimelike.py(528)_validate_comparison_value()
-> other = self._scalar_from_string(other)
> ...\lib\site-packages\pandas\core\arrays\period.py(331)_scalar_from_string()
-> return Period(value, freq=self.freq)
如您所见,在执行实际比较之前,字符串'2022Q1'
gets converted到a Period
,因此Period('2022Q1')
与Period('2022Q1')
的比较是True
.
我不确定这种转换是故意行为还是bug.
至于你问题中的断言部分:将一个序列与某物进行比较会得到一个布尔序列.在条件(if
或assert
)中使用一系列布尔值时,结果必须正好是一个True
或False
值,而不是一系列True
或False
值.正如错误消息所说,您需要决定如何将布尔序列减少为单个布尔.在特殊情况下,序列只有一个元素,但它是一个序列,因此存在误差(对于长度为1的序列,如果使用any
或all
或仅[0]
,则当然没有区别).