사전을 pandas dataframe으로 변환하는 방법(예제 2개)


다음 방법 중 하나를 사용하여 Python의 사전을 pandas DataFrame으로 변환할 수 있습니다.

방법 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()를 사용하여 사전을 DataFrame으로 변환

Python에 다음 사전이 있다고 가정합니다.

 #create dictionary
some_dict = {'Lebron':26,'Luka':30,'Steph':22,'Nicola':29, 'Giannis':31}

다음 코드를 사용하여 이 사전을 pandas DataFrame으로 변환할 수 있습니다.

 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 Luke 30
2 Steph 22
3 Nicola 29
4 Giannis 31

type() 함수를 사용하여 결과가 pandas DataFrame인지 확인할 수도 있습니다.

 #display type of df
type(df)

pandas.core.frame.DataFrame

예제 2: from_dict()를 사용하여 사전을 DataFrame으로 변환

Python에 다음 사전이 있다고 가정합니다.

 #create dictionary
some_dict = {'Lebron':26,'Luka':30,'Steph':22,'Nicola':29, 'Giannis':31}

다음 코드를 사용하여 이 사전을 pandas DataFrame으로 변환할 수 있습니다.

 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 Luke 30
2 Steph 22
3 Nicola 29
4 Giannis 31

type() 함수를 사용하여 결과가 pandas DataFrame인지 확인할 수도 있습니다.

 #display type of df
type(df)

pandas.core.frame.DataFrame

이 방법은 이전 방법과 정확히 동일한 결과를 생성합니다.

추가 리소스

다음 튜토리얼에서는 Pandas에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.

Pandas DataFrame을 사전으로 변환하는 방법
Pandas PivotTable을 DataFrame으로 변환하는 방법
Pandas GroupBy 출력을 DataFrame으로 변환하는 방법

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다