Python dictionary to pandas dataframe

Как преобразовать словарь в Pandas DataFrame(примеры 2)

Вы можете использовать один из следующих методов для преобразования словаря в Python в кадр данных pandas:

Способ 1: используйте dict.items()

df = pd.DataFrame(list(some_dict. items ()), columns = ['col1', 'col2']) 

Способ 2: использовать from_dict()

df = pd.DataFrame.from_dict (some_dict, orient='index'). reset_index() df.columns = ['col1', 'col2'] 

Оба метода дают одинаковый результат.

В следующих примерах показано, как использовать каждый метод на практике.

Пример 1. Преобразование словаря в фрейм данных с помощью dict.items()

Предположим, у нас есть следующий словарь в Python:

#create dictionary some_dict =

Мы можем использовать следующий код для преобразования этого словаря в DataFrame pandas:

import pandas as pd #convert dictionary to pandas DataFrame df = pd.DataFrame(list(some_dict. items ()), columns = ['Player', 'Points']) #view DataFrame df Player Points 0 Lebron 26 1 Luka 30 2 Steph 22 3 Nicola 29 4 Giannis 31 

Мы также можем использовать функцию type() , чтобы подтвердить, что результатом является DataFrame pandas:

#display type of df type(df) pandas.core.frame.DataFrame 

Пример 2: преобразование словаря в фрейм данных с помощью from_dict()

Предположим, у нас есть следующий словарь в Python:

#create dictionary some_dict =

Мы можем использовать следующий код для преобразования этого словаря в DataFrame pandas:

import pandas as pd #convert dictionary to pandas DataFrame df = pd.DataFrame.from_dict (some_dict, orient='index'). reset_index() #define column names of DataFrame df.columns = ['Player', 'Points'] #view DataFrame df Player Points 0 Lebron 26 1 Luka 30 2 Steph 22 3 Nicola 29 4 Giannis 31 

Мы также можем использовать функцию type() , чтобы подтвердить, что результатом является DataFrame pandas:

#display type of df type(df) pandas.core.frame.DataFrame 

Обратите внимание, что этот метод дает точно такой же результат, как и предыдущий метод.

Дополнительные ресурсы

В следующих руководствах объясняется, как выполнять другие распространенные задачи в pandas:

Источник

pandas.DataFrame.from_dict#

Construct DataFrame from dict of array-like or dicts.

Creates DataFrame object from dictionary by columns or by index allowing dtype specification.

Parameters data dict

orient , default ‘columns’

The “orientation” of the data. If the keys of the passed dict should be the columns of the resulting DataFrame, pass ‘columns’ (default). Otherwise if the keys should be rows, pass ‘index’. If ‘tight’, assume a dict with keys [‘index’, ‘columns’, ‘data’, ‘index_names’, ‘column_names’].

New in version 1.4.0: ‘tight’ as an allowed value for the orient argument

Data type to force after DataFrame construction, otherwise infer.

columns list, default None

Column labels to use when orient=’index’ . Raises a ValueError if used with orient=’columns’ or orient=’tight’ .

DataFrame from structured ndarray, sequence of tuples or dicts, or DataFrame.

DataFrame object creation using constructor.

Convert the DataFrame to a dictionary.

By default the keys of the dict become the DataFrame columns:

>>> data = 'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']> >>> pd.DataFrame.from_dict(data) col_1 col_2 0 3 a 1 2 b 2 1 c 3 0 d 

Specify orient=’index’ to create the DataFrame using dictionary keys as rows:

>>> data = 'row_1': [3, 2, 1, 0], 'row_2': ['a', 'b', 'c', 'd']> >>> pd.DataFrame.from_dict(data, orient='index') 0 1 2 3 row_1 3 2 1 0 row_2 a b c d 

When using the ‘index’ orientation, the column names can be specified manually:

>>> pd.DataFrame.from_dict(data, orient='index', . columns=['A', 'B', 'C', 'D']) A B C D row_1 3 2 1 0 row_2 a b c d 

Specify orient=’tight’ to create the DataFrame using a ‘tight’ format:

>>> data = 'index': [('a', 'b'), ('a', 'c')], . 'columns': [('x', 1), ('y', 2)], . 'data': [[1, 3], [2, 4]], . 'index_names': ['n1', 'n2'], . 'column_names': ['z1', 'z2']> >>> pd.DataFrame.from_dict(data, orient='tight') z1 x y z2 1 2 n1 n2 a b 1 3 c 2 4 

Источник

Как преобразовать словарь Python в Pandas DataFrame

Как преобразовать словарь Python в Pandas DataFrame

  1. Метод преобразования отрицательного в Pandas DataFame
  2. Метод преобразования ключей в столбцы и значений в строки значения в Pandas DataFrame
  3. pandas.DataFrame().from_dict() метод для преобразования dict в DataFrame

Мы познакомим вас с методом преобразования Pythonского отрицательного словаря в Pandas datafarme , а также с такими опциями, как наличие ключей в качестве столбцов и значений в качестве страниц и преобразование вложенного отрицательного словаря в DataFrame .

Мы также внедрим другой подход, используя pandas.DataFrame.from_dict , мы свяжем это с любым методом переименования , а также зададим имена индексов и столбцов одним махом.

Метод преобразования отрицательного в Pandas DataFame

Pandas DataFrame конструктор pd.DataFrame() преобразует словарь в DataFrame , если в качестве аргумента конструктора указан элементы словаря, а не сам словарь.

# python 3.x import pandas as pd  fruit_dict =   3: 'apple',  2: 'banana',  6:'mango',  4:'apricot',  1:'kiwi',  8:'orange'>  print(pd.DataFrame(list(fruit_dict.items()),  columns=['Quantity', 'FruitName'])) 

Клавиши и значения словаря преобразуются в две колонки DataFrame с именами столбцов, как указано в опциях столбцы .

 Quantity FruitName 0 3 apple 1 2 banana 2 6 mango 3 4 apricot 4 1 kiwi 5 8 orange 

Метод преобразования ключей в столбцы и значений в строки значения в Pandas DataFrame

Мы можем просто заключить словарь в скобки и удалить название столбца из приведенного выше кода вот так:

import pandas as pd  fruit_dict =   1: 'apple',  2: 'banana',  3:'mango',  4:'apricot',  5:'kiwi',  6:'orange'>  print(pd.DataFrame([fruit_dict])) 
 1 2 3 4 5 6 0 apple banana mango apricot kiwi orange 

Мы используем панды понимания противоречий с concat , чтобы совместить все отрицания , а затем передадим список, чтобы дать новое название столбцам.

import pandas as pd  data =   '1':  'apple':11,  'banana':18>,  '2':  'apple':16,  'banana':12> > df = pd.concat(.Series(v) for k, v in data.items()>).reset_index() df.columns = ['dict_index', 'name','quantity'] print(df) 
 dict_index name quantity 0 1 apple 11 1 1 banana 18 2 2 apple 16 3 2 banana 12 

pandas.DataFrame().from_dict() метод для преобразования dict в DataFrame

Мы будем использовать from_dict для преобразования dict в DataFrame , здесь мы устанавливаем orient=’index’ для использования ключей словаря в качестве строк и применяем метод raname() для изменения имени столбца.

import pandas as pd  print(pd.DataFrame.from_dict(  'apple': 3,  'banana': 5,  'mango': 7,  'apricot': 1,  'kiwi': 8,  'orange': 3>, orient='index').rename(columns=0:'Qunatity'>)) 
 Quantity apple 3 banana 5 mango 7 apricot 1 kiwi 8 orange 3 

Сопутствующая статья — Pandas DataFrame

Copyright © 2023. All right reserved

Источник

How to create DataFrame from a dictionary in Python?

Create DataFrame From Dictionary

Hello there! In this tutorial, we are going to discuss the different ways to create a Pandas DataFrame object from a dictionary in Python. So, let’s get started.

Create a DataFrame from dictionary of lists

In Python, we can easily create a Pandas DataFrame object from a Python dictionary. Let’s learn the different ways to create a pandas DataFrame from a dictionary of lists one by one.

1. Using the pd.DataFrame() function

In this method, we will first create a Python dictionary of lists and pass it to the pd.DataFrame() function. Finally, the pd.DataFrame() function returns a pandas DataFrame object with the data from the dictionary of lists. Let’s implement this through Python code.

# Import pandas module import pandas as pd # Create a Python dictionary of lists data = # Create a pandas DataFrame dictionary of lists # using pd.DataFrame() function df = pd.DataFrame(data) print(df)

Create A DataFrame Using DataFrame Function

2. Using the DataFrame.from_dict() function

Like the previous method, here also we will first create a Python dictionary of lists but pass it to the DataFrame.from_dict() function. Finally, the DataFrame.from_dict() function returns a Pandas DataFrame object with the data from the dictionary of lists. Let’s see how to implement this through Python code.

# Import pandas module import pandas as pd # Create a Python dictionary of lists data = # Create a DataFrame from dictionary of lists # using from_dict() function df = pd.DataFrame.from_dict(data) print(df)

Create A DataFrame Using DataFrame Function

Create a DataFrame from list of dictionaries

In Python, we can also create a Pandas DataFrame object from a list of dictionaries. In this method, we first create a Python list of dictionaries and pass it to the pd.DataFrame() function. Then the pd.DataFrame() function returns a Pandas DataFrame object with the data from the list of dictionaries. Let’s see how to create a DataFrame from a list of dictionaries through Python code.

# Import pandas module import pandas as pd # Create a Python list of dictionaries data = [, , , ,] # Create a DataFrame from list of dictionaries # using pd.DataFrame() function df = pd.DataFrame(data) print(df)

Create A DataFrame From List Of Dictionaries

Create a DataFrame from dictionary of Python ranges

In Python, we can even create a Pandas DataFrame object from a dictionary of Python ranges. In this method, we first create a dictionary of ranges using the range() function in Python and pass it to the pd.DataFrame() function. Then the pd.DataFrame() function returns a Pandas DataFrame object with the data from the dictionary of ranges. Let’s see how to create a DataFrame from a dictionary of Python ranges through Python code.

# Import pandas module import pandas as pd # Create a dictionary of # Python ranges data = # Create a DataFrame from a dictionary # of Python ranges # using pd.DataFrame() function df = pd.DataFrame(data) print(df)

Create A DataFrame From Dictionary Of Python Ranges

Create a DataFrame from dictionary with user-defined indexes

In Python, we can create a Pandas DataFrame object from a dictionary with user-defined indexes. In this method, we first create a Python dictionary and pass it to the pd.DataFrame() function along with the index list. Then the pd.DataFrame() function returns a Pandas DataFrame object with the data from the dictionary and index from the passed index list. Let’s see how to implement it through Python code.

# Import pandas module import pandas as pd # Create a Python dictionary of lists data = # Create a DataFrame from dictionary of lists # using pd.DataFrame() function with user-defined indexes df = pd.DataFrame(data, index = ['S1', 'S2', 'S3', 'S4']) print(df)

Create A DataFrame From Dictionary With User Defined Indexes

Conclusion

In this tutorial, we have learned the different ways to create a Pandas DataFrame object from a Python dictionary. Hope you have understood the things discussed above and ready to explore & learn more about pandas DataFrame objects. Stay tuned with us!

Источник

Читайте также:  Таблица
Оцените статью