Skip to content

use is_integer in df.insert #53194

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
May 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you convert non stdlib ints to satisfy typing checks?

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 "
Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/frame/indexing/test_insert.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add the GH issue number?

# 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]}))