Как преобразовать словарь в серию панд?
Давайте обсудим, как преобразовать словарь в серию панд в Python . Серия - это одномерный помеченный массив, который может содержать данные любого типа, например целые числа, числа с плавающей запятой, строку, объекты Python и т. Д., В то время как словарь представляет собой неупорядоченный набор пар ключ: значение. Мы используем функцию series () библиотеки pandas, чтобы преобразовать словарь в серию, передав словарь в качестве аргумента.
Давайте посмотрим на несколько примеров:
Example 1: We pass the name of dictionary as an argument in series() function. The order of output will be same as of dictionary.
Python3
# Import pandas libraryimport pandas as pd # Create a dictionaryd = {"g" : 100, "e" : 200, "k" : 400, "s" : 800, "n" : 1600} # Convert from dictionary to seriesresult_series = pd.Series(d) # Print seriesresult_series |
Выход:
Example 2: We pass the name of dictionary and a different order of index. The order of output will be same as the order we passed in the argument.
Python3
# Import pandas libraryimport pandas as pd # Create a dictionaryd = {"a" : 10, "b" : 20, "c" : 40, "d" :80, "e" :160} # Convert from dictionary to seriesresult_series = pd.Series(d, index = ["e", "b", "d", "a", "c"])# Print seriesresult_series |
Выход:
Example 3: In the above example the length of index list was same as the number of keys in the dictionary. What happens if they are not equal let’s see with the help of an example.
Python3
# Import pandas libraryimport pandas as pd # Create a dictionaryd = {"a" : 10, "b" : 20, "c" : 40, "d":80} # Convert from dictionary to seriesresult_series = pd.Series(d, index = ["b", "d", "e", "a", "c"])# Print seriesresult_series |
Выход:
Таким образом, этому соответствующему индексу присваивается значение NaN.
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.