Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas cast all levels of a multi-index to another type

Tags:

I have a multi-index and I would like to convert all of its levels to float.

I'm doing the following:

        my_dataframe.index.map(lambda i: (float(i[0]), float(i[1])))

However this does not seem to "scale" very well if I have many levels.

I tried this:

        my_dataframe.index.astype(np.float, copy=False)

but it fails with a TypeError:

TypeError: Setting <class 'pandas.core.indexes.multi.MultiIndex'> dtype to anything other than object is not supported

What would be the best/easiest way to achieve this?

like image 670
Cedric H. Avatar asked Jul 22 '18 09:07

Cedric H.


People also ask

How does pandas handle multiple index columns?

A multi-index dataframe has multi-level, or hierarchical indexing. We can easily convert the multi-level index into the column by the reset_index() method. DataFrame. reset_index() is used to reset the index to default and make the index a column of the dataframe.


1 Answers

You can use get_level_values for select levels, convert to floats and last :

a = my_dataframe.index.get_level_values(0).astype(float)
b = my_dataframe.index.get_level_values(1).astype(float)

my_dataframe.index = [a,b]

Or:

my_dataframe = my_dataframe.set_index([a,b])

Another solution with MultiIndex.set_levels:

a = my_dataframe.index.levels[0].astype(float)
b = my_dataframe.index.levels[1].astype(float)
my_dataframe.index = my_dataframe.index.set_levels([a,b])

Or:

my_dataframe = my_dataframe.set_index(my_dataframe.index.set_levels([a,b]))
like image 64
jezrael Avatar answered Oct 11 '22 12:10

jezrael