Skip to content

Instantly share code, notes, and snippets.

@jkokorian
Created November 1, 2016 12:33
Show Gist options
  • Save jkokorian/d907633fe3e3479604f455b3b0317f05 to your computer and use it in GitHub Desktop.
Save jkokorian/d907633fe3e3479604f455b3b0317f05 to your computer and use it in GitHub Desktop.
from collections import namedtuple
def seriesToTuple(s,name="IndexTuple"):
"""
Converts pandas Series `s` to a named tuple.
Args:
s (pd.Series): pandas Series object to convert
name (str): name of the resulting NamedTuple class
Returns:
NamedTuple: an instance of a newly created namedtuple class with the same properties as the index values of `s`.
"""
assert not s.index.has_duplicates
assert len(s.index) < 50
assert all([type(ix) in [unicode,str] for ix in s.index])
T = namedtuple(s.name.strip().replace(' ','') if s.name is not None else name," ".join(s.index))
return T(*s.values)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment