Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Inplace #1266

Closed
wants to merge 4 commits into from

2 participants

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on May 13, 2012
  1. ENH: inplace keyword to DataFrame.rename #207

    Chang She authored
  2. ENH: inplace Series.rename

    Chang She authored
Commits on May 16, 2012
  1. ENH: inplace option for sort_index

    Chang She authored
Commits on May 21, 2012
This page is out of date. Refresh to see the latest.
View
32 pandas/core/frame.py
@@ -2388,7 +2388,8 @@ def duplicated(self, cols=None, take_last=False):
#----------------------------------------------------------------------
# Sorting
- def sort(self, columns=None, column=None, axis=0, ascending=True):
+ def sort(self, columns=None, column=None, axis=0, ascending=True,
+ inplace=False):
"""
Sort DataFrame either by labels (along either axis) or by the values in
column(s)
@@ -2402,6 +2403,8 @@ def sort(self, columns=None, column=None, axis=0, ascending=True):
Sort ascending vs. descending
axis : {0, 1}
Sort index/rows versus columns
+ inplace : boolean, default False
+ Sort the DataFrame without creating a new instance
Returns
-------
@@ -2411,9 +2414,10 @@ def sort(self, columns=None, column=None, axis=0, ascending=True):
import warnings
warnings.warn("column is deprecated, use columns", FutureWarning)
columns = column
- return self.sort_index(by=columns, axis=axis, ascending=ascending)
+ return self.sort_index(by=columns, axis=axis, ascending=ascending,
+ inplace=inplace)
- def sort_index(self, axis=0, by=None, ascending=True):
+ def sort_index(self, axis=0, by=None, ascending=True, inplace=False):
"""
Sort DataFrame either by labels (along either axis) or by the values in
a column
@@ -2427,6 +2431,8 @@ def sort_index(self, axis=0, by=None, ascending=True):
for a nested sort.
ascending : boolean, default True
Sort ascending vs. descending
+ inplace : boolean, default False
+ Sort the DataFrame without creating a new instance
Returns
-------
@@ -2449,7 +2455,18 @@ def sort_index(self, axis=0, by=None, ascending=True):
if not ascending:
indexer = indexer[::-1]
- return self.take(indexer, axis=axis)
+ if inplace:
+ if axis == 1:
+ self._data = self._data.reindex_items(self._data.items[indexer],
+ copy=False)
+ elif axis == 0:
+ self._data = self._data.take(indexer)
+ else:
+ raise ValueError('Axis must be 0 or 1, got %s' % str(axis))
+ self._clear_item_cache()
+ return self
+ else:
+ return self.take(indexer, axis=axis)
def sortlevel(self, level=0, axis=0, ascending=True):
"""
@@ -2610,7 +2627,7 @@ def fillna(self, value=None, method='pad', axis=0, inplace=False,
#----------------------------------------------------------------------
# Rename
- def rename(self, index=None, columns=None, copy=True):
+ def rename(self, index=None, columns=None, copy=True, inplace=False):
"""
Alter index and / or columns using input function or
functions. Function / dict values must be unique (1-to-1). Labels not
@@ -2624,6 +2641,9 @@ def rename(self, index=None, columns=None, copy=True):
Transformation to apply to column values
copy : boolean, default True
Also copy underlying data
+ inplace : boolean, default False
+ Whether to return a new DataFrame. If True then value of copy is
+ ignored.
See also
--------
@@ -2643,7 +2663,7 @@ def rename(self, index=None, columns=None, copy=True):
self._consolidate_inplace()
- result = self.copy(deep=copy)
+ result = self if inplace else self.copy(deep=copy)
if index is not None:
result._rename_index_inplace(index_f)
View
4 pandas/core/series.py
@@ -2377,7 +2377,7 @@ def interpolate(self, method='linear'):
return Series(result, index=self.index, name=self.name)
- def rename(self, mapper):
+ def rename(self, mapper, inplace=False):
"""
Alter Series index using dict or function
@@ -2412,7 +2412,7 @@ def rename(self, mapper):
renamed : Series (new object)
"""
mapper_f = _get_rename_function(mapper)
- result = self.copy()
+ result = self if inplace else self.copy()
result.index = [mapper_f(x) for x in self.index]
return result
View
62 pandas/tests/test_frame.py
@@ -3807,6 +3807,19 @@ def test_rename_nocopy(self):
renamed['foo'] = 1.
self.assert_((self.frame['C'] == 1.).all())
+ def test_rename_inplace(self):
+ self.frame.rename(columns={'C' : 'foo'})
+ self.assert_('C' in self.frame)
+ self.assert_('foo' not in self.frame)
+
+ c_id = id(self.frame['C'])
+ frame = self.frame.copy()
+ frame.rename(columns={'C' : 'foo'}, inplace=True)
+ self.assert_('C' not in frame)
+ self.assert_('foo' in frame)
+ self.assert_(id(frame['foo']) != c_id)
+
+
#----------------------------------------------------------------------
# Time series related
@@ -4261,6 +4274,55 @@ def test_sort_index_multicolumn(self):
expected = frame.take(indexer)
assert_frame_equal(result, expected)
+ def test_sort_index_inplace(self):
+ frame = DataFrame(np.random.randn(4, 4), index=[1, 2, 3, 4],
+ columns=['A', 'B', 'C', 'D'])
+
+ # axis=0
+ unordered = frame.ix[[3, 2, 4, 1]]
+ a_id = id(unordered['A'])
+ df = unordered.copy()
+ df.sort_index(inplace=True)
+ expected = frame
+ assert_frame_equal(df, expected)
+ self.assert_(a_id != id(df['A']))
+
+ df = unordered.copy()
+ df.sort_index(ascending=False, inplace=True)
+ expected = frame[::-1]
+ assert_frame_equal(df, expected)
+
+ # axis=1
+ unordered = frame.ix[:, ['D', 'B', 'C', 'A']]
+ df = unordered.copy()
+ df.sort_index(axis=1, inplace=True)
+ expected = frame
+ assert_frame_equal(df, expected)
+
+ df = unordered.copy()
+ df.sort_index(axis=1, ascending=False, inplace=True)
+ expected = frame.ix[:, ::-1]
+ assert_frame_equal(df, expected)
+
+ def test_sort_inplace(self):
+ frame = DataFrame(np.random.randn(4, 4), index=[1, 2, 3, 4],
+ columns=['A', 'B', 'C', 'D'])
+
+ sorted_df = frame.copy()
+ sorted_df.sort(columns='A', inplace=True)
+ expected = frame.sort_index(by='A')
+ assert_frame_equal(sorted_df, expected)
+
+ sorted_df = frame.copy()
+ sorted_df.sort(columns='A', ascending=False, inplace=True)
+ expected = frame.sort_index(by='A', ascending=False)
+ assert_frame_equal(sorted_df, expected)
+
+ sorted_df = frame.copy()
+ sorted_df.sort(columns=['A', 'B'], ascending=False, inplace=True)
+ expected = frame.sort_index(by=['A', 'B'], ascending=False)
+ assert_frame_equal(sorted_df, expected)
+
def test_frame_column_inplace_sort_exception(self):
s = self.frame['A']
self.assertRaises(Exception, s.sort)
View
6 pandas/tests/test_series.py
@@ -2374,6 +2374,12 @@ def test_rename(self):
renamed = s.rename({'b' : 'foo', 'd' : 'bar'})
self.assert_(np.array_equal(renamed.index, ['a', 'foo', 'c', 'bar']))
+ def test_rename_inplace(self):
+ renamer = lambda x: x.strftime('%Y%m%d')
+ expected = renamer(self.ts.index[0])
+ self.ts.rename(renamer, inplace=True)
+ self.assertEqual(self.ts.index[0], expected)
+
def test_preserveRefs(self):
seq = self.ts[[5,10,15]]
seq[1] = np.NaN
Something went wrong with that request. Please try again.