Skip to content

Commit 71bb9ba

Browse files
committed
ENH: Refactor code to add is_view method for Series.
1 parent ee92c75 commit 71bb9ba

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

pandas/core/series.py

Lines changed: 15 additions & 6 deletions
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

Lines changed: 7 additions & 0 deletions
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)