6

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?

Cedric H.
  • 7,980
  • 10
  • 55
  • 82

2 Answers2

6

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]))
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

If you df.columns is a MultiIndex and you want to cast all levels of a multi-index column names to another type, say int to str, then you might find this useful:

pivot_2d.columns = [pivot_2d.columns.get_level_values(i).astype(str) for i in range(len(pivot_2d.columns.levels)

or even better:

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

Good luck!

Daniel Moraite
  • 422
  • 5
  • 8