pandas: convert index type in multiindex dataframe

Question:

Hi have a multiindex dataframe:

tuples = [('YTA_Q3', 1), ('YTA_Q3', 2), ('YTA_Q3', 3), ('YTA_Q3', 4), ('YTA_Q3', 99), ('YTA_Q3', 96)]
# Index
index = pd.MultiIndex.from_tuples(tuples, names=['Questions', 'Values'])
# Columns
columns = pd.MultiIndex.from_tuples([('YTA_Q3', '@')], names=['Questions', 'Values'])
# Data
data = [29.014949,5.0260590000000001,
  6.6269119999999999,
  1.3565260000000001,
  41.632221999999999,
  21.279499999999999]

df1 = pd.DataFrame(data=data, index=index, columns=columns)

How do I convert the inner values of the df’s index to str?

My attempt:

df1.index.astype(str) 

returns a TypeError

Asked By: Boosted_d16

||

Answers:

IIUC you need the last level of Multiindex. You could access it with levels:

df1.index.levels[-1].astype(str)

In [584]: df1.index.levels[-1].astype(str)
Out[584]: Index(['1', '2', '3', '4', '96', '99'], dtype='object', name='Values')

EDIT

You could set your inner level with set_levels method of multiIndex:

idx = df1.index
df1.index = df1.index.set_levels([idx.levels[:-1], idx.levels[-1].astype(str)])
Answered By: Anton Protopopov

I find the current pandas implementation a bit cumbersome, so I use this:

df1.index = pd.MultiIndex.from_tuples([(ix[0], str(ix[1])) for ix in df1.index.tolist()])

Answered By: FuzzyDuck

There was change in pandas and old way doesn’t work properly.

For me this worked.

level_to_change = 1
df.index = df.index.set_levels(df.index.levels[level_to_change].astype(int), level=level_to_change)
Answered By: Jsowa

Very late to the party, but if you also want to maintain the names on your multi-index levels, I’d suggest the following:

df_ts.index = pd.MultiIndex.from_frame(
    pd.DataFrame(index=df_ts.index)
    .reset_index().astype(int)
    )

Similarly if you have multi-index columns, you can use:

df_ts.columns = pd.MultiIndex.from_frame(
        pd.DataFrame(index=df_ts.columns)
        .reset_index().astype(int)
        )
Answered By: DaveB
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.