Skip to content

Commit

Permalink
BUG: Fixed strange behaviour of pd.DataFrame.drop() with inplace argu…
Browse files Browse the repository at this point in the history
  • Loading branch information
rjfs committed Dec 27, 2019
1 parent 710df21 commit 55ababc
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 42 deletions.
42 changes: 0 additions & 42 deletions pandas/core/ops/methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,48 +83,6 @@ def add_special_arithmetic_methods(cls):
new_methods = _create_methods(
cls, arith_method, comp_method, bool_method, special=True
)
# inplace operators (I feel like these should get passed an `inplace=True`
# or just be removed

def _wrap_inplace_method(method):
"""
return an inplace wrapper for this method
"""

def f(self, other):
result = method(self, other)

# this makes sure that we are aligned like the input
# we are updating inplace so we want to ignore is_copy
self._update_inplace(
result.reindex_like(self, copy=False)._data, verify_is_copy=False
)

return self

f.__name__ = "__i{name}__".format(name=method.__name__.strip("__"))
return f

new_methods.update(
dict(
__iadd__=_wrap_inplace_method(new_methods["__add__"]),
__isub__=_wrap_inplace_method(new_methods["__sub__"]),
__imul__=_wrap_inplace_method(new_methods["__mul__"]),
__itruediv__=_wrap_inplace_method(new_methods["__truediv__"]),
__ifloordiv__=_wrap_inplace_method(new_methods["__floordiv__"]),
__imod__=_wrap_inplace_method(new_methods["__mod__"]),
__ipow__=_wrap_inplace_method(new_methods["__pow__"]),
)
)

new_methods.update(
dict(
__iand__=_wrap_inplace_method(new_methods["__and__"]),
__ior__=_wrap_inplace_method(new_methods["__or__"]),
__ixor__=_wrap_inplace_method(new_methods["__xor__"]),
)
)

_add_methods(cls, new_methods=new_methods)


Expand Down
21 changes: 21 additions & 0 deletions pandas/tests/base/test_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,27 @@ def test_drop_duplicates_series_vs_dataframe(self):
dropped_series = df[column].drop_duplicates(keep=keep)
tm.assert_frame_equal(dropped_frame, dropped_series.to_frame())

def test_inplace_drop_and_add(self):
# GH 30484
# Get expected df
expected = pd.DataFrame({})
expected["x1"] = [1, 2, 3, 4, 5]
expected["x2"] = [0, 0, 0, 1, 1]
expected["target"] = [10, 20, 30, 40, 50]
y = expected["target"]
expected.drop("target", axis=1, inplace=True)
y = y + np.min(y)
# Get tested df
df = pd.DataFrame({})
df["x1"] = [1, 2, 3, 4, 5]
df["x2"] = [0, 0, 0, 1, 1]
df["target"] = [10, 20, 30, 40, 50]
y = df["target"]
df.drop("target", axis=1, inplace=True)
y += np.min(y)
# compare
tm.assert_frame_equal(df, expected)

def test_fillna(self):
# # GH 11343
# though Index.fillna and Series.fillna has separate impl,
Expand Down

0 comments on commit 55ababc

Please sign in to comment.