Skip to content

Commit c6d8a31

Browse files
Chang Shewesm
Chang She
authored andcommitted
ENH: inplace Series.rename
1 parent eb80a1c commit c6d8a31

File tree

3 files changed

+15
-5
lines changed

3 files changed

+15
-5
lines changed

pandas/core/internals.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -103,18 +103,22 @@ def merge(self, other):
103103
return _merge_blocks([self, other], self.ref_items)
104104

105105
def reindex_axis(self, indexer, mask, needs_masking, axis=0,
106-
fill_value=np.nan):
106+
fill_value=np.nan, out=None):
107107
"""
108108
Reindex using pre-computed indexer information
109109
"""
110110
if self.values.size > 0:
111111
new_values = com.take_fast(self.values, indexer, mask,
112112
needs_masking, axis=axis,
113-
fill_value=fill_value)
113+
fill_value=fill_value,
114+
out=out)
114115
else:
115116
shape = list(self.shape)
116117
shape[axis] = len(indexer)
117-
new_values = np.empty(shape)
118+
if out is not None and (out.shape == shape):
119+
new_values = out
120+
else:
121+
new_values = np.empty(shape)
118122
new_values.fill(fill_value)
119123
return make_block(new_values, self.items, self.ref_items)
120124

pandas/core/series.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -2460,7 +2460,7 @@ def interpolate(self, method='linear'):
24602460

24612461
return Series(result, index=self.index, name=self.name)
24622462

2463-
def rename(self, mapper):
2463+
def rename(self, mapper, inplace=False):
24642464
"""
24652465
Alter Series index using dict or function
24662466
@@ -2495,7 +2495,7 @@ def rename(self, mapper):
24952495
renamed : Series (new object)
24962496
"""
24972497
mapper_f = _get_rename_function(mapper)
2498-
result = self.copy()
2498+
result = self if inplace else self.copy()
24992499
result.index = [mapper_f(x) for x in self.index]
25002500

25012501
return result

pandas/tests/test_series.py

+6
Original file line numberDiff line numberDiff line change
@@ -2375,6 +2375,12 @@ def test_rename(self):
23752375
renamed = s.rename({'b' : 'foo', 'd' : 'bar'})
23762376
self.assert_(np.array_equal(renamed.index, ['a', 'foo', 'c', 'bar']))
23772377

2378+
def test_rename_inplace(self):
2379+
renamer = lambda x: x.strftime('%Y%m%d')
2380+
expected = renamer(self.ts.index[0])
2381+
self.ts.rename(renamer, inplace=True)
2382+
self.assertEqual(self.ts.index[0], expected)
2383+
23782384
def test_preserveRefs(self):
23792385
seq = self.ts[[5,10,15]]
23802386
seq[1] = np.NaN

0 commit comments

Comments
 (0)