For arbitrary level of the column value
If the level of the column index shall be arbitrary, this might help you a bit:
class DataFrameMultiColumn(pd.DataFrame) :
def loc_multicolumn(self, keys):
depth = lambda L: isinstance(L, list) and max(map(depth, L))+1
result = []
col = self.columns
# if depth of keys is 1, all keys need to be true
if depth(keys) == 1:
for c in col:
# select all columns which contain all keys
if set(keys).issubset(set(c)) :
result.append(c)
# depth of 2 indicates,
# the product of all sublists will be formed
elif depth(keys) == 2 :
keys = list(itertools.product(*keys))
for c in col:
for k in keys :
# select all columns which contain all keys
if set(k).issubset(set(c)) :
result.append(c)
else :
raise ValueError("Depth of the keys list exceeds 2")
# return with .loc command
return self.loc[:,result]
.loc_multicolumn
will return the same as calling .loc
but without specifing the level for each key.
Please note that this might be a problem is values are the same in multiple column levels!
Example :
Sample data:
np.random.seed(1)
col = pd.MultiIndex.from_arrays([['one', 'one', 'one', 'two', 'two', 'two'],
['a', 'b', 'c', 'a', 'b', 'c']])
data = pd.DataFrame(np.random.randint(0, 10, (4,6)), columns=col)
data_mc = DataFrameMultiColumn(data)
>>> data_mc
one two
a b c a b c
0 5 8 9 5 0 0
1 1 7 6 9 2 4
2 5 2 4 2 4 7
3 7 9 1 7 0 6
Cases:
List depth 1 requires all elements in the list be fit.
>>> data_mc.loc_multicolumn(['a', 'one'])
one
a
0 5
1 1
2 5
3 7
>>> data_mc.loc_multicolumn(['a', 'b'])
Empty DataFrame
Columns: []
Index: [0, 1, 2, 3]
>>> data_mc.loc_multicolumn(['one','a', 'b'])
Empty DataFrame
Columns: []
Index: [0, 1, 2, 3]
List depth 2 allows all elements of the Cartesian product of keys list.
>>> data_mc.loc_multicolumn([['a', 'b']])
one two
a b a b
0 5 8 5 0
1 1 7 9 2
2 5 2 2 4
3 7 9 7 0
>>> data_mc.loc_multicolumn([['one'],['a', 'b']])
one
a b
0 5 8
1 1 7
2 5 2
3 7 9
For the last:
All combination from list(itertools.product(["one"], ['a', 'b']))
are given if all elements in the combination fits.
data.xs(['a', 'c'], axis=1, level=1)
loc
along with thepd.IndexSlice
API which is now the preferred way of slicing MultIndexs. See this answer, and this post.