Repository: pandas-dev/pandas

Issue:
BUG: not reproducible error `FloatingPointError: overflow encountered in multiply` in the following sequence: read_csv followed by to_datetime with pandas version 2.2.2
### Pandas version checks

- [X] I have checked that this issue has not already been reported.

- [X] I have confirmed this bug exists on the [latest version](https://pandas.pydata.org/docs/whatsnew/index.html) of pandas.

- [ ] I have confirmed this bug exists on the [main branch](https://pandas.pydata.org/docs/dev/getting_started/install.html#installing-the-development-version-of-pandas) of pandas.


### Reproducible Example

```python
import pandas as pd

for ii in range(10000):
    df = pd.read_csv("data.csv", dtype={"ts": float})   # data.csv provided in an attached file
    pd.to_datetime(df["ts"], unit="s", errors="coerce")
```


### Issue Description

I, sometimes, get the following error with pandas 2.2.2 (I don't have this error with pandas 2.1.4):

> Exception has occurred: FloatingPointError
> overflow encountered in multiply
>   File ".../main.py", line 218, in <module>
>     pd.to_datetime(df["ts"], unit="s", errors="coerce")
> FloatingPointError: overflow encountered in multiply

The error is not repeatable, hence the loop. I tried to reduce as much as possible the input file while keeping the raised error, this is why I provided a csv file with 200 rows, attached to this issue. I don't know if the issue is due to the `read_csv` (I got the same problem with `read_parquet`) or due to `to_datetime`. If the `read_csv` is outside the loop and I make a deepcopy at the beginning of each loop, I don't have the problem, so my hunch is that this is linked to the reading process (`read_csv` in the example).

### Expected Behavior

I expect the loop content to have the same behaviour, works every time or fails every time.

### Installed Versions

<details>

INSTALLED VERSIONS
------------------
commit                : d9cdd2ee5a58015ef6f4d15c7226110c9aab8140
python                : 3.11.8.final.0
python-bits           : 64
OS                    : Linux
OS-release            : 5.15.0-105-generic
Version               : #115~20.04.1-Ubuntu SMP Mon Apr 15 17:33:04 UTC 2024
machine               : x86_64
processor             : x86_64
byteorder             : little
LC_ALL                : None
LANG                  : en_US.UTF-8
LOCALE                : en_US.UTF-8

pandas                : 2.2.2
numpy                 : 1.26.4
pytz                  : 2024.1
dateutil              : 2.9.0.post0
setuptools            : 65.5.0
pip                   : 24.0
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               : None
pandas_datareader     : None
adbc-driver-postgresql: None
adbc-driver-sqlite    : None
bs4                   : None
bottleneck            : None
dataframe-api-compat  : None
fastparquet           : None
fsspec                : None
gcsfs                 : None
matplotlib            : None
numba                 : None
numexpr               : None
odfpy                 : None
openpyxl              : None
pandas_gbq            : None
pyarrow               : 16.0.0
pyreadstat            : None
python-calamine       : None
pyxlsb                : None
s3fs                  : None
scipy                 : None
sqlalchemy            : None
tables                : None
tabulate              : None
xarray                : None
xlrd                  : None
zstandard             : None
tzdata                : 2024.1
qtpy                  : None
pyqt5                 : None

</details>

[data.csv](https://github.com/pandas-dev/pandas/files/15109625/data.csv)



Discussion:

Patch:
diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml
index a4c2a732f9..4da2b0b84a 100644
--- a/.github/workflows/wheels.yml
+++ b/.github/workflows/wheels.yml
@@ -153,7 +153,7 @@ jobs:
         run: echo "sdist_name=$(cd ./dist && ls -d */)" >> "$GITHUB_ENV"
 
       - name: Build wheels
-        uses: pypa/cibuildwheel@v2.22.0
+        uses: pypa/cibuildwheel@v2.23.0
         with:
          package-dir: ./dist/${{ startsWith(matrix.buildplat[1], 'macosx') && env.sdist_name || needs.build_sdist.outputs.sdist_file }}
         env:
diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst
index b5bd3216dd..c967b97cb2 100644
--- a/doc/source/whatsnew/v3.0.0.rst
+++ b/doc/source/whatsnew/v3.0.0.rst
@@ -649,6 +649,7 @@ Datetimelike
 - Bug in :meth:`DatetimeIndex.union` and :meth:`DatetimeIndex.intersection` when ``unit`` was non-nanosecond (:issue:`59036`)
 - Bug in :meth:`Series.dt.microsecond` producing incorrect results for pyarrow backed :class:`Series`. (:issue:`59154`)
 - Bug in :meth:`to_datetime` not respecting dayfirst if an uncommon date string was passed. (:issue:`58859`)
+- Bug in :meth:`to_datetime` on float array with missing values throwing ``FloatingPointError`` (:issue:`58419`)
 - Bug in :meth:`to_datetime` on float32 df with year, month, day etc. columns leads to precision issues and incorrect result. (:issue:`60506`)
 - Bug in :meth:`to_datetime` reports incorrect index in case of any failure scenario. (:issue:`58298`)
 - Bug in :meth:`to_datetime` wrongly converts when ``arg`` is a ``np.datetime64`` object with unit of ``ps``. (:issue:`60341`)
@@ -692,6 +693,7 @@ Indexing
 ^^^^^^^^
 - Bug in :meth:`DataFrame.__getitem__` returning modified columns when called with ``slice`` in Python 3.12 (:issue:`57500`)
 - Bug in :meth:`DataFrame.from_records` throwing a ``ValueError`` when passed an empty list in ``index`` (:issue:`58594`)
+- Bug in :meth:`DataFrame.loc` with inconsistent behavior of loc-set with 2 given indexes to Series (:issue:`59933`)
 - Bug in :meth:`MultiIndex.insert` when a new value inserted to a datetime-like level gets cast to ``NaT`` and fails indexing (:issue:`60388`)
 - Bug in printing :attr:`Index.names` and :attr:`MultiIndex.levels` would not escape single quotes (:issue:`60190`)
 
diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx
index 7a8b4df447..c4acf72ab8 100644
--- a/pandas/_libs/tslibs/conversion.pyx
+++ b/pandas/_libs/tslibs/conversion.pyx
@@ -137,7 +137,7 @@ def cast_from_unit_vectorized(
 
     out = np.empty(shape, dtype="i8")
     base = np.empty(shape, dtype="i8")
-    frac = np.empty(shape, dtype="f8")
+    frac = np.zeros(shape, dtype="f8")
 
     for i in range(len(values)):
         if is_nan(values[i]):
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 8a493fef54..bcb27d0320 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -2349,11 +2349,17 @@ class _iLocIndexer(_LocationIndexer):
 
         if isinstance(indexer, tuple):
             # flatten np.ndarray indexers
+            if (
+                len(indexer) == 2
+                and isinstance(indexer[1], np.ndarray)
+                and indexer[1].dtype == np.bool_
+            ):
+                indexer = (indexer[0], np.where(indexer[1])[0])
+
             def ravel(i):
                 return i.ravel() if isinstance(i, np.ndarray) else i
 
             indexer = tuple(map(ravel, indexer))
-
             aligners = [not com.is_null_slice(idx) for idx in indexer]
             sum_aligners = sum(aligners)
             single_aligner = sum_aligners == 1
@@ -2371,12 +2377,15 @@ class _iLocIndexer(_LocationIndexer):
 
             # we have a frame, with multiple indexers on both axes; and a
             # series, so need to broadcast (see GH5206)
-            if sum_aligners == self.ndim and all(is_sequence(_) for _ in indexer):
+            if all(is_sequence(_) or isinstance(_, slice) for _ in indexer):
                 ser_values = ser.reindex(obj.axes[0][indexer[0]])._values
 
                 # single indexer
                 if len(indexer) > 1 and not multiindex_indexer:
-                    len_indexer = len(indexer[1])
+                    if isinstance(indexer[1], slice):
+                        len_indexer = len(obj.axes[1][indexer[1]])
+                    else:
+                        len_indexer = len(indexer[1])
                     ser_values = (
                         np.tile(ser_values, len_indexer).reshape(len_indexer, -1).T
                     )


Test patch:
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py
index 17e610bda9..8838fc7eed 100644
--- a/pandas/tests/indexing/test_loc.py
+++ b/pandas/tests/indexing/test_loc.py
@@ -3296,6 +3296,66 @@ class TestLocSeries:
         expected = DataFrame(index=[1, 1, 2, 2], data=["1", "1", "2", "2"])
         tm.assert_frame_equal(df, expected)
 
+    @pytest.mark.parametrize(
+        "df, row_index, col_index, expected_df",
+        [
+            [
+                DataFrame([[1, 2, 3], [4, 5, 6]], columns=list("ABC")),
+                slice(0, 3),
+                ["A", "B", "C"],
+                DataFrame([[10, 10, 10], [20, 20, 20]], columns=list("ABC")),
+            ],
+            [
+                DataFrame([[1, 2, 3], [4, 5, 6]], columns=list("ABC")),
+                slice(None),
+                ["A", "B", "C"],
+                DataFrame([[10, 10, 10], [20, 20, 20]], columns=list("ABC")),
+            ],
+            [
+                DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=list("ABC")),
+                [True, True, True],
+                ["A", "B", "C"],
+                DataFrame(
+                    [[10, 10, 10], [20, 20, 20], [30, 30, 30]], columns=list("ABC")
+                ),
+            ],
+            [
+                DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=list("ABC")),
+                slice(0, 4),
+                ["A", "B", "C"],
+                DataFrame(
+                    [[10, 10, 10], [20, 20, 20], [30, 30, 30]], columns=list("ABC")
+                ),
+            ],
+            [
+                DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=list("ABC")),
+                slice(None),
+                slice("A", "C"),
+                DataFrame(
+                    [[10, 10, 10], [20, 20, 20], [30, 30, 30]], columns=list("ABC")
+                ),
+            ],
+            [
+                DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=list("ABC")),
+                slice(None),
+                Series(
+                    {
+                        "A": True,
+                        "C": False,
+                        "B": True,
+                    }
+                ),
+                DataFrame([[10, 10, 3], [20, 20, 6], [30, 30, 9]], columns=list("ABC")),
+            ],
+        ],
+    )
+    def test_loc_set_series_to_multiple_columns(
+        self, df, row_index, col_index, expected_df
+    ):
+        # GH 59933
+        df.loc[row_index, col_index] = Series([10, 20, 30])
+        tm.assert_frame_equal(df, expected_df)
+
     def test_loc_setitem_matching_index(self):
         # GH 25548
         s = Series(0.0, index=list("abcd"))
diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index e039f54960..616ae36c98 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -2520,6 +2520,15 @@ class TestToDatetimeMisc:
         with pytest.raises(OutOfBoundsTimedelta, match=msg):
             date_range(start="1/1/1700", freq="B", periods=100000)
 
+    def test_to_datetime_float_with_nans_floating_point_error(self):
+        # GH#58419
+        ser = Series([np.nan] * 1000 + [1712219033.0], dtype=np.float64)
+        result = to_datetime(ser, unit="s", errors="coerce")
+        expected = Series(
+            [NaT] * 1000 + [Timestamp("2024-04-04 08:23:53")], dtype="datetime64[ns]"
+        )
+        tm.assert_series_equal(result, expected)
+
     def test_string_invalid_operation(self, cache):
         invalid = np.array(["87156549591102612381000001219H5"], dtype=object)
         # GH #51084