Skip to content

Commit 89a65d2

Browse files
committed
FIX #4554 and other issues with Series.reshape()
1 parent 60d7fce commit 89a65d2

File tree

3 files changed

+19
-10
lines changed

3 files changed

+19
-10
lines changed

doc/source/release.rst

+2
Original file line numberDiff line numberDiff line change
@@ -498,6 +498,8 @@ Bug Fixes
498498
- ``Timestamp`` objects can now appear in the left hand side of a comparison
499499
operation with a ``Series`` or ``DataFrame`` object (:issue:`4982`).
500500
- Fix a bug when indexing with ``np.nan`` via ``iloc/loc`` (:issue:`5016`)
501+
- Fix a bug where reshaping a ``Series`` to its own shape raised ``TypeError`` (:issue:`4554`)
502+
and other reshaping issues.
501503

502504
pandas 0.12.0
503505
-------------

pandas/core/series.py

+11-8
Original file line numberDiff line numberDiff line change
@@ -1152,18 +1152,21 @@ def repeat(self, reps):
11521152
new_values = self.values.repeat(reps)
11531153
return self._constructor(new_values, index=new_index, name=self.name)
11541154

1155-
def reshape(self, newshape, order='C'):
1155+
def reshape(self, *args, **kwargs):
11561156
"""
11571157
See numpy.ndarray.reshape
11581158
"""
1159-
if order not in ['C', 'F']:
1160-
raise TypeError(
1161-
"must specify a tuple / singular length to reshape")
1162-
1163-
if isinstance(newshape, tuple) and len(newshape) > 1:
1164-
return self.values.reshape(newshape, order=order)
1159+
if len(args) == 1 and hasattr(args[0], '__iter__'):
1160+
shape = args[0]
11651161
else:
1166-
return ndarray.reshape(self, newshape, order)
1162+
shape = args
1163+
1164+
if tuple(shape) == self.shape:
1165+
# XXX ignoring the "order" keyword.
1166+
return self
1167+
1168+
return self.values.reshape(shape, **kwargs)
1169+
11671170

11681171
def get(self, label, default=None):
11691172
"""

pandas/tests/test_series.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -1046,12 +1046,16 @@ def test_basic_getitem_setitem_corner(self):
10461046
[5, slice(None, None)], 2)
10471047

10481048
def test_reshape_non_2d(self):
1049+
# GH 4554
10491050
x = Series(np.random.random(201), name='x')
1050-
self.assertRaises(TypeError, x.reshape, (len(x),))
1051+
self.assertTrue(x.reshape(x.shape,) is x)
10511052

10521053
# GH 2719
10531054
a = Series([1, 2, 3, 4])
1054-
self.assertRaises(TypeError, a.reshape, 2, 2)
1055+
result = a.reshape(2, 2)
1056+
expected = a.values.reshape(2, 2)
1057+
np.testing.assert_array_equal(result, expected)
1058+
self.assertTrue(type(result) is type(expected))
10551059

10561060
def test_reshape_2d_return_array(self):
10571061
x = Series(np.random.random(201), name='x')

0 commit comments

Comments
 (0)