Skip to content

raise more specific error if dict is appended to frame wit… #30882

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 3 commits into from
Jan 20, 2020
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
3 changes: 2 additions & 1 deletion doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,8 @@ ExtensionArray

Other
^^^^^
-
- Appending a dictionary to a :class:`DataFrame` without passing ``ignore_index=True`` will raise ``TypeError: Can only append a dict if ignore_index=True``
instead of ``TypeError: Can only append a Series if ignore_index=True or if the Series has a name`` (:issue:`30871`)
-

.. ---------------------------------------------------------------------------
Expand Down
2 changes: 2 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -7062,6 +7062,8 @@ def append(
"""
if isinstance(other, (Series, dict)):
if isinstance(other, dict):
if not ignore_index:
Copy link
Member

Choose a reason for hiding this comment

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

Rather than adding another branch here can you just use an f-string and do f"Can only append a {type(other)}...

Copy link
Member Author

Choose a reason for hiding this comment

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

Could do, but then I'll need to add another branch later as the message for Series has an extra part compared to that for dict: "or if the Series has a name"

raise TypeError("Can only append a dict if ignore_index=True")
other = Series(other)
if other.name is None and not ignore_index:
raise TypeError(
Expand Down
4 changes: 4 additions & 0 deletions pandas/tests/frame/methods/test_append.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ def test_append_series_dict(self):
)
tm.assert_frame_equal(result, expected.loc[:, result.columns])

msg = "Can only append a dict if ignore_index=True"
with pytest.raises(TypeError, match=msg):
df.append(series.to_dict())

# can append when name set
row = df.loc[4]
row.name = 5
Expand Down