Python | Панды Dataframe.to_dict ()
Python - отличный язык для анализа данных, в первую очередь из-за фантастической экосистемы пакетов Python, ориентированных на данные. Pandas - один из таких пакетов, который значительно упрощает импорт и анализ данных.
Pandas .to_dict()
method is used to convert a dataframe into a dictionary of series or list like data type depending on orient parameter.
Syntax: DataFrame.to_dict(orient=’dict’, into=)
Parameters:
orient: String value, (‘dict’, ‘list’, ‘series’, ‘split’, ‘records’, ‘index’) Defines which dtype to convert Columns(series into). For example, ‘list’ would return a dictionary of lists with Key=Column name and Value=List (Converted series).
into: class, can pass an actual class or instance. For example in case of defaultdict instance of class can be passed. Default value of this parameter is dict.Return type: Dataframe converted into Dictionary
Чтобы загрузить набор данных, используемый в следующем примере, щелкните здесь.
В следующих примерах используемый фрейм данных содержит данные некоторых игроков НБА. Изображение фрейма данных до каких-либо операций прилагается ниже.
Example #1: Default conversion into dictionary of Dictionaries
In this case, no parameter is passed to the to_dict()
method. Hence it will convert the dataframe in to a dictionary of dictionaries by default.
# importing pandas module import pandas as pd # reading csv file from url # dropping null value columns to avoid errors data.dropna(inplace = True ) # converting to dict data_dict = data.to_dict() # display data_dict |
Выход:
Как показано на выходном изображении, словарь словарей был возвращен методом to_dict (). Ключ первого словаря - это имя столбца, а столбец хранится с индексом как ключ второго словаря.
Пример # 2: преобразование в словарь серий
In this example, ‘series’ is passed to the orient parameter to convert the data frame into Dictionary of Series.
# importing pandas module import pandas as pd # reading csv file from url # dropping null value columns to avoid errors data.dropna(inplace = True ) # converting to dict data_dict = data.to_dict( "series" ) # printing datatype of first keys value in dict print ( type (data_dict[ "Name" ])) # display data_dict |
Выход:
Как показано на выходном изображении, поскольку тип data_dict ['Name'] был pandas.core.series.Series, to_dict () вернул словарь серий.
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.