Skip to content

Commit 6521f04

Browse files
Chang Shewesm
Chang She
authored andcommitted
ENH: overwrite keyword in DataFrame.update
1 parent 681f739 commit 6521f04

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

pandas/core/frame.py

+9-2
Original file line numberDiff line numberDiff line change
@@ -3143,7 +3143,7 @@ def combine_first(self, other):
31433143
combiner = lambda x, y: np.where(isnull(x), y, x)
31443144
return self.combine(other, combiner)
31453145

3146-
def update(self, other, join='left'):
3146+
def update(self, other, join='left', overwrite=True):
31473147
"""
31483148
Modify DataFrame in place using non-NA values from passed
31493149
DataFrame. Aligns on indices
@@ -3152,6 +3152,9 @@ def update(self, other, join='left'):
31523152
----------
31533153
other : DataFrame
31543154
join : {'left', 'right', 'outer', 'inner'}, default 'left'
3155+
overwrite : boolean, default True
3156+
If True then overwrite values for common keys in the calling
3157+
frame
31553158
"""
31563159
if join != 'left':
31573160
raise NotImplementedError
@@ -3160,7 +3163,11 @@ def update(self, other, join='left'):
31603163
for col in self.columns:
31613164
this = self[col].values
31623165
that = other[col].values
3163-
self[col] = np.where(isnull(that), this, that)
3166+
if overwrite:
3167+
mask = isnull(that)
3168+
else:
3169+
mask = notnull(this)
3170+
self[col] = np.where(mask, this, that)
31643171

31653172
#----------------------------------------------------------------------
31663173
# Misc methods

pandas/tests/test_frame.py

+17
Original file line numberDiff line numberDiff line change
@@ -5235,6 +5235,23 @@ def test_update(self):
52355235
[1.5, nan, 7.]])
52365236
assert_frame_equal(df, expected)
52375237

5238+
def test_update_nooverwrite(self):
5239+
df = DataFrame([[1.5, nan, 3.],
5240+
[1.5, nan, 3.],
5241+
[1.5, nan, 3],
5242+
[1.5, nan, 3]])
5243+
5244+
other = DataFrame([[3.6, 2., np.nan],
5245+
[np.nan, np.nan, 7]], index=[1, 3])
5246+
5247+
df.update(other, overwrite=False)
5248+
5249+
expected = DataFrame([[1.5, nan, 3],
5250+
[1.5, 2, 3],
5251+
[1.5, nan, 3],
5252+
[1.5, nan, 3.]])
5253+
assert_frame_equal(df, expected)
5254+
52385255
def test_combineAdd(self):
52395256
# trivial
52405257
comb = self.frame.combineAdd(self.frame)

0 commit comments

Comments
 (0)