Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas: convert index type in multiindex dataframe

Tags:

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

like image 344
Boosted_d16 Avatar asked Dec 22 '15 14:12

Boosted_d16


People also ask

How do I change the index type in pandas DataFrame?

To change the type of a DataFrame's index in Pandas, use the DataFrame. index. astype(~) method.

How do I convert MultiIndex to single index in pandas?

To revert the index of the dataframe from multi-index to a single index using the Pandas inbuilt function reset_index(). Returns: (Data Frame or None) DataFrame with the new index or None if inplace=True.

How do you replace an index in a data frame?

Pandas DataFrame: set_index() function The set_index() function is used to set the DataFrame index using existing columns. Set the DataFrame index (row labels) using one or more existing columns or arrays of the correct length. The index can replace the existing index or expand on it.


1 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)]) 
like image 111
Anton Protopopov Avatar answered Sep 19 '22 19:09

Anton Protopopov