извлекать мультииндексные типы в пандах - PullRequest
0 голосов
/ 26 мая 2018

У меня есть датафрейм, где я set_index(), используя 3 столбца.Я хотел бы извлечь тип данных, связанный с каждым индексом.Как я могу сделать это эффективно?Я не хочу делать type(df.index.get_level_values()), так как df большой.

MWE:

import pandas as pd
df = pd.DataFrame({"id": [1,2,1,2], "time": [1, 1, 2, 2], "val": [1,2,3,4]})
df.set_index(keys=["id", "time"], inplace=True)
type(df.index.get_level_values(1))
#pandas.core.indexes.numeric.Int64Index

Я также хотел бы знать тип фактических данных в индексе(т.е. глядя на это я знаю, что это целые числа, но было бы неплохо получить что-то вроде этого также:

type(df.index.get_level_values(1).values[0])
#numpy.int64

1 Ответ

0 голосов
/ 26 мая 2018

Вы можете использовать [lev.dtype.type for lev in index.levels]:

import pandas as pd
df = pd.DataFrame({"id": [1,2,1,2], "time": [1, 1, 2, 2], "val": [1,2,3,4]})
df.set_index(keys=["id", "time"], inplace=True)
index = df.index

print([lev.dtype.type for lev in index.levels])
# [<class 'numpy.int64'>, <class 'numpy.int64'>]

# Alternatively, there is the private attribute, `_inferred_type_levels`,  
# but this is probably not what you are looking for.
print(index._inferred_type_levels)
# ['integer', 'integer']

index.levels - это FrozenList одномерных индексов:

In [172]: list(index.levels)
Out[172]: 
[Int64Index([1, 2], dtype='int64', name='id'),
 Int64Index([1, 2], dtype='int64', name='time')]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...