Description
While adding an equals()
method to ExtensionArray (#27081, #30652), some questions come up about how strict the method should be:
- Other array-likes are not equivalent, even if they are all equal?
- But subclasses are equivalent, when they are all equal?
- Objects with different dtype are not equivalent (eg int8 vs int16), even if all values are equal?
And it seems that right now, we are somewhat inconsistent with this in pandas regarding being strict on the data type.
Series is strict about the dtype, while Index is not:
>>> pd.Series([1, 2, 3], dtype="int64").equals(pd.Series([1, 2, 3], dtype="int32"))
False
>>> pd.Index([1, 2, 3], dtype="int64").equals(pd.Index([1, 2, 3], dtype="int32"))
True
For Index, this not only gives True for different integer dtypes as above, but also for float/int, object/int (both examples give False for Series):
>>> pd.Index([1, 2, 3], dtype="int64").equals(pd.Index([1, 2, 3], dtype="object"))
True
>>> pd.Index([1, 2, 3], dtype="int64").equals(pd.Index([1, 2, 3], dtype="float64"))
True
Index and Series are consistent when it comes to not being equal with other array-likes:
# all those cases return False
pd.Series([1, 2, 3]).equals(np.array([1, 2, 3]))
pd.Index([1, 2, 3]).equals(np.array([1, 2, 3]))
pd.Series([1, 2, 3]).equals(pd.Index([1, 2, 3]))
pd.Index([1, 2, 3]).equals(pd.Series([1, 2, 3]))
pd.Series([1, 2, 3]).equals([1, 2, 3])
pd.Index([1, 2, 3]).equals([1, 2, 3])
Both Index and Series also seem to allow subclasses:
class MySeries(pd.Series):
pass
>>> pd.Series([1, 2, 3]).equals(MySeries([1, 2, 3]))
True
So in the end, I think the main discussion point is: should the dtype be exactly the same, or should only the values be equal?
For DataFrame, it shares the implementation with Series so follows that behaviour (except that for DataFrame there are some additional rules about how column names need to compare equal).