Skip to content

BUG: ensure Series.name is hashable, #12610 #12612

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions doc/source/whatsnew/v0.18.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,8 @@ Bug Fixes


- Bug in ``pivot_table`` when ``margins=True`` and ``dropna=True`` where nulls still contributed to margin count (:issue:`12577`)




Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just put this higher up, in the existing space, so you aren't adding lines

- Bug in ``Series.name`` when ``name`` attribute can be hashable type (:issue:`12610`)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

a hashable type

2 changes: 1 addition & 1 deletion pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ class NDFrame(PandasObject):
copy : boolean, default False
"""
_internal_names = ['_data', '_cacher', '_item_cache', '_cache', 'is_copy',
'_subtyp', '_index', '_default_kind',
'_subtyp', '_name', '_index', '_default_kind',
'_default_fill_value', '_metadata', '__array_struct__',
'__array_interface__']
_internal_names_set = set(_internal_names)
Expand Down
12 changes: 11 additions & 1 deletion pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ def __init__(self, data=None, index=None, dtype=None, name=None,

generic.NDFrame.__init__(self, data, fastpath=True)

object.__setattr__(self, 'name', name)
self.name = name
self._set_axis(0, index, fastpath=True)

@classmethod
Expand Down Expand Up @@ -301,6 +301,16 @@ 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)

@property
def name(self):
return self._name

@name.setter
def name(self, value):
if value is not None and not com.is_hashable(value):
raise TypeError('Series.name must be a hashable type')
object.__setattr__(self, '_name', value)

# ndarray compatibility
@property
def dtype(self):
Expand Down
6 changes: 4 additions & 2 deletions pandas/tests/series/test_alter_axes.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# coding=utf-8
# pylint: disable-msg=E1101,W0612

from datetime import datetime

import numpy as np
import pandas as pd

Expand Down Expand Up @@ -64,15 +66,15 @@ def test_rename_by_series(self):

def test_rename_set_name(self):
s = Series(range(4), index=list('abcd'))
for name in ['foo', ['foo'], ('foo',)]:
for name in ['foo', 123, 123., datetime(2001, 11, 11), ('foo',)]:
result = s.rename(name)
self.assertEqual(result.name, name)
self.assert_numpy_array_equal(result.index.values, s.index.values)
self.assertTrue(s.name is None)

def test_rename_set_name_inplace(self):
s = Series(range(3), index=list('abc'))
for name in ['foo', ['foo'], ('foo',)]:
for name in ['foo', 123, 123., datetime(2001, 11, 11), ('foo',)]:
s.rename(name, inplace=True)
self.assertEqual(s.name, name)
self.assert_numpy_array_equal(s.index.values,
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/series/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -725,3 +725,14 @@ def f():
self.assertEqual(s.dtype, 'timedelta64[ns]')
s = Series([pd.NaT, np.nan, '1 Day'])
self.assertEqual(s.dtype, 'timedelta64[ns]')

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can do these in 2 tests. _hashable, and _unhashable. just put a loop in each one.

def test_constructor_name_hashable(self):
for n in [777, 777., 'name', datetime(2001, 11, 11), (1, 2)]:
for data in [[1, 2, 3], np.ones(3), {'a': 0, 'b': 1}]:
s = Series(data, name=n)
self.assertEqual(s.name, n)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

need to add similar tests for setting .name (search for where these existing tests are).

e.g.

s = Series(data)
s.name = n

type things

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here: https://github.com/pydata/pandas/blob/master/pandas/tests/series/test_alter_axes.py#L80

(add a new test), you can use some of the test_repr examples (e.g. unicode and such)


def test_constructor_name_unhashable(self):
for n in [['name_list'], np.ones(2), {1: 2}]:
for data in [['name_list'], np.ones(2), {1: 2}]:
self.assertRaises(TypeError, Series, data, name=n)
5 changes: 3 additions & 2 deletions pandas/tests/series/test_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,9 @@ def test_timeseries_periodindex(self):
self.assertEqual(new_ts.index.freq, 'M')

def test_pickle_preserve_name(self):
unpickled = self._pickle_roundtrip_name(self.ts)
self.assertEqual(unpickled.name, self.ts.name)
for n in [777, 777., 'name', datetime(2001, 11, 11), (1, 2)]:
unpickled = self._pickle_roundtrip_name(tm.makeTimeSeries(name=n))
self.assertEqual(unpickled.name, n)

def _pickle_roundtrip_name(self, obj):

Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/series/test_repr.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,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))
Expand Down