Skip to content
This repository has been archived by the owner on Apr 10, 2024. It is now read-only.

Commit

Permalink
Modifications to column-hierarchical behaviour as per "'Mixed depth' …
Browse files Browse the repository at this point in the history
…hierarchical column labels'" discussion on pystatsmodels.

If column label tuples contain only empty strings at the lower levels, allows the DataFrame to be indexed with only the higher levels. So for example if a column has the hierarchical label ('a','',''), and there are no other columns with 'a' at their top level, then this change allows the column to be pulled out with df['a'], rather than df['a','','']. It also names the resulting series 'a'. 
The use case for this is when some columns have a deeper hierarchy than others, and you want to treat the shallower columns as if the lower levels of the hierarchy weren't there.
  • Loading branch information
chrisjbillington authored and wesm committed Feb 9, 2012
1 parent 8e03572 commit 428896d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
5 changes: 5 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -1429,6 +1429,11 @@ def _getitem_multilevel(self, key):
new_values = self.values[:, loc]
result = DataFrame(new_values, index=self.index,
columns=result_columns)
if len(result.columns) == 1:
top = result.columns[0]
if (type(top) == str and top == '' or
type(top) == tuple and top[0] == ''):
result = Series(result[''], index=self.index, name=key)
return result
else:
return self._get_item_cache(key)
Expand Down
16 changes: 15 additions & 1 deletion pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,21 @@ def __delitem__(self, key):
"""
Delete item
"""
self._data.delete(key)
deleted = False
if key not in self.columns:
# If column labels are tuples, allow shorthand to delete
# all columns whose first len(key) elements match key:
if not isinstance(key,tuple):
key = (key,)
for col in self.columns:
if isinstance(col,tuple) and col[:len(key)] == key:
del self[col]
deleted = True
if not deleted:
# If the above loop ran and didn't delete anything because
# there was no match, this call should raise the appropriate
# exception:
self._data.delete(key)

try:
del self._item_cache[key]
Expand Down

0 comments on commit 428896d

Please sign in to comment.