Description
Pandas version checks
-
I have checked that this issue has not already been reported.
-
I have confirmed this bug exists on the latest version of pandas.
-
I have confirmed this bug exists on the main branch of pandas.
Reproducible Example
x = pd.Series(index=['a', 'b'], dtype='f4')
x.iloc[0] = 1.02
print(x.dtype)
Issue Description
In 2.1.1, this code prints the following warning:
FutureWarning: Setting an item of incompatible dtype is deprecated and will raise in a future error of pandas. Value '1.02' has dtype incompatible with float32, please explicitly cast to a compatible dtype first.
It then shows that the post-assignment dtype is float64
, which is presumably why the warning is being raised: Pandas is converting the backing array from f4 to f8 behind the scenes for some reason.
Do you really intend this to raise an exception in the future? It seems like it would be better to just assign the literal to to the existing float32 array. I checked what earlier versions of Pandas did, and it looks like Pandas 1.4.4 kept the dtype as float32 after the assignment, while Pandas 1.5.2 changes the dtype to float64. I'm not sure whether that was intentional or not - it doesn't seem to be explicitly called out in the release notes for e.g. 1.5.0 (though it's possible I missed something).
The warning can of course be suppressed by writing np.float32(1.02)
instead of the simple literal, but it doesn't seem great to require users to write this kind of stuff for every literal assignment.
Expected Behavior
Just assign the literal to the float32 array with no warning and no exception about dtype conversion.
Installed Versions
pandas : 2.1.1
numpy : 1.23.5
pytz : 2023.3
dateutil : 2.8.2
setuptools : 67.7.2
pip : 23.1.2
Cython : 3.0.0
pytest : 7.3.1
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.9.2
html5lib : 1.1
pymysql : None
psycopg2 : None
jinja2 : 3.1.2
IPython : 8.13.2
pandas_datareader : None
bs4 : 4.12.2
bottleneck : 1.3.7
dataframe-api-compat: None
fastparquet : None
fsspec : 2023.6.0
gcsfs : None
matplotlib : 3.7.1
numba : 0.56.4
numexpr : 2.8.7
odfpy : None
openpyxl : 3.1.2
pandas_gbq : None
pyarrow : 10.0.1
pyreadstat : None
pyxlsb : None
s3fs : 2023.6.0
scipy : 1.10.1
sqlalchemy : None
tables : None
tabulate : None
xarray : 2023.4.2
xlrd : 2.0.1
zstandard : None
tzdata : 2023.3
qtpy : 2.3.1
pyqt5 : None