diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index 52fc8512c9db3..e659bf7adbf1a 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -351,6 +351,7 @@ Conversion - Bug in :meth:`ArrowDtype.numpy_dtype` returning nanosecond units for non-nanosecond ``pyarrow.timestamp`` and ``pyarrow.duration`` types (:issue:`51800`) - Bug in :meth:`DataFrame.__repr__` incorrectly raising a ``TypeError`` when the dtype of a column is ``np.record`` (:issue:`48526`) - Bug in :meth:`DataFrame.info` raising ``ValueError`` when ``use_numba`` is set (:issue:`51922`) +- Bug in :meth:`DataFrame.insert` raising ``TypeError`` if ``loc`` is ``np.int64`` (:issue:`53193`) - Strings diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 485cc9db5ffe7..459b162e2a6c9 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4800,9 +4800,10 @@ def insert( if not allow_duplicates and column in self.columns: # Should this be a different kind of error?? raise ValueError(f"cannot insert {column}, already exists") - if not isinstance(loc, int): + if not is_integer(loc): raise TypeError("loc must be int") - + # convert non stdlib ints to satisfy typing checks + loc = int(loc) if isinstance(value, DataFrame) and len(value.columns) > 1: raise ValueError( f"Expected a one-dimensional object, got a DataFrame with " diff --git a/pandas/tests/frame/indexing/test_insert.py b/pandas/tests/frame/indexing/test_insert.py index 666a6ec3710a6..13e43abe0dd7f 100644 --- a/pandas/tests/frame/indexing/test_insert.py +++ b/pandas/tests/frame/indexing/test_insert.py @@ -110,3 +110,9 @@ def test_insert_frame(self): ) with pytest.raises(ValueError, match=msg): df.insert(1, "newcol", df) + + def test_insert_int64_loc(self): + # GH#53193 + df = DataFrame({"a": [1, 2]}) + df.insert(np.int64(0), "b", 0) + tm.assert_frame_equal(df, DataFrame({"b": [0, 0], "a": [1, 2]}))