Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the dtype of a pandas multiindex

How can I find the dtype of a MultiIndex in pandas without printing out all the values (this happens if you type df.index, for example). I just want to know the names of the indices and their types.

Ex:

df = pd.DataFrame({"a": np.arange(100000), "b": np.arange(100000)[::-1]}, index=pd.MultiIndex.from_arrays([np.arange(100000), np.arange(100000)[::-1]], names=["i1", "i2"]))

doing:

df.index

will take some time to actually print, for a large df that's too long.

like image 357
Alex Avatar asked Jun 28 '18 21:06

Alex


People also ask

What is a MultiIndex in pandas?

The MultiIndex object is the hierarchical analogue of the standard Index object which typically stores the axis labels in pandas objects. You can think of MultiIndex as an array of tuples where each tuple is unique. A MultiIndex can be created from a list of arrays (using MultiIndex.

What does the pandas function MultiIndex From_tuples do?

from_tuples() function is used to convert list of tuples to MultiIndex. It is one of the several ways in which we construct a MultiIndex.


2 Answers

Use get_level_values:

df.index.get_level_values(0).dtype
dtype('int64')

and

df.index.get_level_values(1).dtype
dtype('int64')

For names use:

df.index.names
FrozenList(['i1', 'i2'])
like image 193
Scott Boston Avatar answered Sep 22 '22 07:09

Scott Boston


pandas >= 1.3 [est]

Coming soon to a distro near you, you MultiIndex.dtypes will soon be available:

df.index.dtypes

i1    int64
i2    int64
dtype: object 

For older versions, if your index is not too large, you can first convert to a frame using to_frame, then query the dtypes:

df.index.to_frame().dtypes

i1    int64
i2    int64
dtype: object
like image 44
cs95 Avatar answered Sep 23 '22 07:09

cs95