diff --git a/pandas/core/series.py b/pandas/core/series.py index 081e5c50946bc..7ce783278b86f 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -17,6 +17,7 @@ _default_index, _maybe_upcast, _asarray_tuplesafe, _infer_dtype_from_scalar, is_list_like, _values_from_object, + is_hashable, _possibly_cast_to_datetime, _possibly_castable, _possibly_convert_platform, _try_sort, ABCSparseArray, _maybe_match_name, _coerce_to_dtype, @@ -105,6 +106,8 @@ class Series(base.IndexOpsMixin, generic.NDFrame): dict. dtype : numpy.dtype or None If None, dtype will be inferred + name : used to attach metadata to a Series, e.g., as str or namedtuple. + Must be hashable, defaults to None. copy : boolean, default False Copy input data """ @@ -272,6 +275,20 @@ def _update_inplace(self, result, **kwargs): # we want to call the generic version and not the IndexOpsMixin return generic.NDFrame._update_inplace(self, result, **kwargs) + # Validate that name is hashable + @property + def name(self): + return self._name + + @name.setter + def name(self, value): + if is_hashable(value): + object.__setattr__(self, '_name', value) + else: + raise TypeError('Series.name must be hashable, got %s.' + % value.__class__.__name__) + + # ndarray compatibility @property def dtype(self): diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index c0daeb793fc40..6c33dcc23a0a7 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -644,6 +644,13 @@ def test_constructor_map(self): result = Series(m, index=lrange(10, 20)) exp.index = lrange(10, 20) assert_series_equal(result, exp) + + def test_constructor_unhashable_name(self): + def set_to_unhashable(s_): + s_.name = {} + s = Series([1,3], name = 'test') + self.assertRaises(TypeError, set_to_unhashable, s) + self.assertEqual(s.name, 'test') def test_constructor_categorical(self): cat = pd.Categorical([0, 1, 2, 0, 1, 2], ['a', 'b', 'c'], fastpath=True) @@ -1980,7 +1987,7 @@ def test_repr(self): rep_str = repr(ser) self.assertIn("Name: 0", rep_str) - ser = Series(["a\n\r\tb"], name=["a\n\r\td"], index=["a\n\r\tf"]) + ser = Series(["a\n\r\tb"], name="a\n\r\td", index=["a\n\r\tf"]) self.assertFalse("\t" in repr(ser)) self.assertFalse("\r" in repr(ser)) self.assertFalse("a\n" in repr(ser))