Python multiindex slicing with repetitive values

You can do this by using your a and b arrays to create a new MultiIndex then reindex your dataframe:

Sample Data

import pandas as pd

index = pd.MultiIndex.from_product([[1,2,3], [1,2,3]])
df = pd.DataFrame({"C": [11, 12, 13, 21, 22, 23, 31, 32, 33]}, index=index)

print(df) # dataframe with 2-level index and 1 column "C"
      C
1 1  11
  2  12
  3  13
2 1  21
  2  22
  3  23
3 1  31
  2  32
  3  33

Method

  • Create new MultiIndex from your a and b arrays
  • Align the dataframe (or just column of interest) to this new index
a = [1, 2, 3, 1, 2, 1, 2 ]
b = [3, 2, 1, 3, 2, 1, 3 ]

new_index = pd.MultiIndex.from_arrays([a, b])
new_c = df["C"].reindex(new_index)

print(new_c.to_numpy())
[13 22 31 13 22 11 23]

Method 2

You can also zip your a and b arrays together and simply use .loc to slice your dataframe:

# Select the rows specified by combinations of a, b; in column "C"
new_c = df.loc[zip(a, b), "C"]

print(new_c.to_numpy())
[13 22 31 13 22 11 23]

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top