Created
December 29, 2017 13:25
-
-
Save jakeemerson/a2d75a4f7a41e4f124e5da856b1fb08c to your computer and use it in GitHub Desktop.
A table-like object that can be sliced like a numpy array. Pure python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Table(list): | |
""" | |
a table object that can be sliced like a numpy array | |
""" | |
def __init__(self, *args, has_header=True): | |
self.has_header = has_header | |
if has_header: | |
self.header_index = {} | |
self.header = args[0][0] | |
self.__make_header_index() | |
list.__init__(self, *args) | |
def __getitem__(self, item): | |
try: | |
return list.__getitem__(self, item) | |
except TypeError: | |
rows, cols = item | |
return [row[cols] for row in self[rows]] | |
def __make_header_index(self): | |
# set up a column heading index for lookups | |
for idx, col_name in enumerate(self.header): | |
self.header_index[col_name] = idx | |
def column_unique(self, col_name): | |
if self.has_header: | |
# use a string to get the index from the header_index | |
return set(self[1:, self.header_index[col_name]]) | |
else: | |
# use an integer index | |
return set(self[0:, col_name]) | |
def column(self, col_name): | |
if self.has_header: | |
# use a string to get the index from the header_index | |
return self[1:, self.header_index[col_name]] | |
else: | |
# use an integer index | |
return self[0:, col_name] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment