Skip to content Skip to sidebar Skip to footer

Get The Row And Column Labels For Selected Values In A Pandas Dataframe

I'd like to get the row and column labels for values matching some condition in a dataframe. Just to keep it interesting, I need it to work with a hierarchical (multi-)index. For

Solution 1:

Use np.where to obtain the ordinal indices of the True values:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.arange(16).reshape(4, 4), 
                  columns=pd.MultiIndex.from_product((('a', 'b'), ('x', 'y'))))

mask = (df % 6 == 0)
i, j = np.where(mask)
print(list(zip(df.index[i], df.columns[j])))

yields

[(0, ('a', 'x')), (1, ('b', 'x')), (3, ('a', 'x'))]

Post a Comment for "Get The Row And Column Labels For Selected Values In A Pandas Dataframe"