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

Commit 428896d

Browse files
chrisjbillingtonwesm
authored andcommitted
Modifications to column-hierarchical behaviour as per "'Mixed depth' 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.
1 parent 8e03572 commit 428896d

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

pandas/core/frame.py

+5
Original file line numberDiff line numberDiff line change
@@ -1429,6 +1429,11 @@ def _getitem_multilevel(self, key):
14291429
new_values = self.values[:, loc]
14301430
result = DataFrame(new_values, index=self.index,
14311431
columns=result_columns)
1432+
if len(result.columns) == 1:
1433+
top = result.columns[0]
1434+
if (type(top) == str and top == '' or
1435+
type(top) == tuple and top[0] == ''):
1436+
result = Series(result[''], index=self.index, name=key)
14321437
return result
14331438
else:
14341439
return self._get_item_cache(key)

pandas/core/generic.py

+15-1
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,21 @@ def __delitem__(self, key):
302302
"""
303303
Delete item
304304
"""
305-
self._data.delete(key)
305+
deleted = False
306+
if key not in self.columns:
307+
# If column labels are tuples, allow shorthand to delete
308+
# all columns whose first len(key) elements match key:
309+
if not isinstance(key,tuple):
310+
key = (key,)
311+
for col in self.columns:
312+
if isinstance(col,tuple) and col[:len(key)] == key:
313+
del self[col]
314+
deleted = True
315+
if not deleted:
316+
# If the above loop ran and didn't delete anything because
317+
# there was no match, this call should raise the appropriate
318+
# exception:
319+
self._data.delete(key)
306320

307321
try:
308322
del self._item_cache[key]

0 commit comments

Comments
 (0)