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?
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.
You can use get_level_values
for select levels, convert to float
s 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]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With