Skip to content

Commit 91d6f1b

Browse files
author
y-p
committed
Merge pull request #5853 from jseabold/add-is-view-series
ENH: Refactor code to add is_view method for Series.
2 parents ee92c75 + ce0f0f7 commit 91d6f1b

File tree

3 files changed

+24
-6
lines changed

3 files changed

+24
-6
lines changed

doc/source/v0.13.1.txt

+2
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ Deprecations
2929
Enhancements
3030
~~~~~~~~~~~~
3131

32+
Added an ``is_view`` method to Series.
33+
3234
Experimental
3335
~~~~~~~~~~~~
3436

pandas/core/series.py

+15-6
Original file line numberDiff line numberDiff line change
@@ -1645,6 +1645,20 @@ def update(self, other):
16451645
#----------------------------------------------------------------------
16461646
# Reindexing, sorting
16471647

1648+
def is_view(self):
1649+
"""
1650+
Return True if series is a view of some other array, False otherwise.
1651+
"""
1652+
true_base = self.values
1653+
while true_base.base is not None:
1654+
true_base = true_base.base
1655+
1656+
if (true_base is not None and
1657+
(true_base.ndim != 1 or true_base.shape != self.shape)):
1658+
return True
1659+
return False
1660+
1661+
16481662
def sort(self, axis=0, kind='quicksort', order=None, ascending=True):
16491663
"""
16501664
Sort values and index labels by value, in place. For compatibility with
@@ -1667,12 +1681,7 @@ def sort(self, axis=0, kind='quicksort', order=None, ascending=True):
16671681
sortedSeries = self.order(na_last=True, kind=kind,
16681682
ascending=ascending)
16691683

1670-
true_base = self.values
1671-
while true_base.base is not None:
1672-
true_base = true_base.base
1673-
1674-
if (true_base is not None and
1675-
(true_base.ndim != 1 or true_base.shape != self.shape)):
1684+
if self.is_view():
16761685
raise TypeError('This Series is a view of some other array, to '
16771686
'sort in-place you must create a copy')
16781687

pandas/tests/test_series.py

+7
Original file line numberDiff line numberDiff line change
@@ -5548,6 +5548,13 @@ def test_unique_data_ownership(self):
55485548
# it works! #1807
55495549
Series(Series(["a", "c", "b"]).unique()).sort()
55505550

5551+
def test_is_view():
5552+
df = tm.makeDataFrame()
5553+
view = df['A'].is_view()
5554+
tm.assert_equal(view, True)
5555+
ser = tm.makeStringSeries()
5556+
view = ser.is_view()
5557+
tm.assert_equal(view, False)
55515558

55525559
if __name__ == '__main__':
55535560
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],

0 commit comments

Comments
 (0)