> ## Content Index
> Fetch the complete content index at: https://datascientyst.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Convert Pandas MultiIndex values to New Type -String, Int
- URL: https://datascientyst.com/convert-pandas-multiindex-values-to-new-type-string-int/
- Published: 2025-05-16T13:22:27.000Z
- Updated: 2025-05-16T13:22:27.000Z
- Author: John D K
- Tags: MultiIndex

Here are a few common ways to convert Pandas `MultiIndex` values to string or other data type:

**(1) Custom conversion per level**

```python
df.index.set_levels(midx.levels[0].astype(int), level=0) \
        .set_levels(midx.levels[1].astype(str), level=1) \
        .set_levels(midx.levels[2].astype(int), level=2)

```

**(2) Conversion to single type**

```python
for level in range(0, len(midx)-1):
    df.index = df.index.set_levels(midx.levels[level].astype(int), level=level)

```

## Example MultiIndex

```python
import pandas as pd

df = pd.DataFrame(
    {"Grade": ["A", "B", "A", "C"]},
    index=[
        ["11", "11", "12", "12"],
        ["21", "22", "21", "22"],
        ["31", "32", "33", "34"]
    ]
)

```

data looks like:

|    |    |    | Grade |
| -- | -- | -- | ----- |
| 11 | 21 | 31 | A     |
| 22 | 32 | B  |       |
| 12 | 21 | 33 | A     |
| 22 | 34 | C  |       |

## 1: Iterate each MultiIndex Level and convert

We can do custom conversion per level by providing the conversion details explicitly:

```python
df.index = df.index.set_levels(midx.levels[0].astype(int), level=0) \
        .set_levels(midx.levels[1].astype(float), level=1) \
        .set_levels(midx.levels[2].astype(int), level=2)

```

Result:

```
MultiIndex([(11, 21.0, 31),
            (11, 22.0, 32),
            (12, 21.0, 33),
            (12, 22.0, 34)],
           )

```

## 2: Automatic conversion of MI to single type

To convert all levels of MultiIndex to a single data types we can use combination of `set_levels` and iteration over each level:

```python
for level in range(0, len(midx)-1):
    df.index = df.index.set_levels(midx.levels[level].astype(int), level=level)

```

## Resources

- [Converting a pandas dataframe with a string type, three level MultiIndex into numeric type objects](https://stackoverflow.com/questions/38620850/converting-a-pandas-dataframe-with-a-string-type-three-level-multiindex-into-nu?ref=datascientyst.com)
- [pandas.MultiIndex.set\_levels](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.set%5Flevels.html?ref=datascientyst.com)