Description
-
I have checked that this issue has not already been reported.
-
I have confirmed this bug exists on the latest version of pandas.
-
(optional) I have confirmed this bug exists on the master branch of pandas.
Code Sample
s_obj = pd.Series(['1', '2', '3'])
s_int = pd.Series([1, 2, 3])
s_obj.isin(s_int).sum() # 0
s_int.isin(s_obj).sum() # 3
s_obj.astype(np.int).isin(s_int).sum() # 3
Problem description
It is not uncommon for numeric fields to be read into a dataframe column as text. The behavior of the isin
function is inconsistent in these cases, working as expected in the s_int.isin(s_obj)
case, but failing in the s_obj.isin(s_int)
case unless the text field is coerced to numeric first by the user.
Expected Output
Behavior should be consistent in both directions. Either isin()
should always fail when there is a type mismatch, or it should perform necessary coersions automatically. It would be helpful to throw a warning in either case to inform the user either that they should standardize their schemas or that a potentially costly coersion is going to happen automatically. At the very least, we could keep the current behavior and show the user a warning explaining that an empty result set could be due to a type mismatch.
Middle ground solution: add something like a coerce_if_necessary
option to isin()
. Defaulting to False would return the current behavior (which preserves backwards compatibility and ensures we don't surprise users with expensive coersions). We could augment this behavior with a new warning, alerting users to the type mismatch and recommending solutions. Users who aren't comfortable with datatypes (or are just feeling lazy) could then set coerce=True
to have necessary coersions attempted for them behind the scenes.
Interested to hear other's thoughts regarding what the preferred behavior should be.
Output of pd.show_versions()
INSTALLED VERSIONS
commit : None
python : 3.8.3.final.0
python-bits : 64
OS : Windows
OS-release : 10
machine : AMD64
processor : Intel64 Family 6 Model 142 Stepping 10, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : English_United States.1252
pandas : 1.0.3
numpy : 1.18.1
pytz : 2020.1
dateutil : 2.8.1
pip : 20.0.2
setuptools : 47.1.1.post20200604
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : 7.13.0
pandas_datareader: None
bs4 : None
bottleneck : None
fastparquet : None
gcsfs : None
lxml.etree : None
matplotlib : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pytables : None
pytest : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
xlsxwriter : None
numba : None