pandas.DataFrame, Seriesを辞書に変換(to_dict)

Modified: | Tags: Python, pandas, 辞書

to_dict()メソッドを使うとpandas.DataFrame, pandas.Seriesを辞書(dict型オブジェクト)に変換できる。

pandas.DataFrameの場合、引数orientによってpandas.DataFrameの行ラベルindex、列ラベルcolumns、値valuesをどのように辞書のkey, valueに割り当てるかの形式を指定できる。

pandas.Seriesの場合は、ラベルがキーとなる辞書に変換される。

ここでは以下の内容を説明する。

  • pandas.DataFrameto_dict()メソッド
    • 辞書の形式を指定: 引数orient
    • dict以外の型に変換: 引数into
  • pandas.DataFrameの任意の2列から辞書生成
  • pandas.Seriesto_dictメソッド
    • dict以外の型に変換: 引数into

例として以下のpandas.DataFrameを作成する。

import pandas as pd
import pprint
from collections import OrderedDict

df = pd.DataFrame({'col1': [1, 2, 3], 'col2': ['a', 'x', 'あ']},
                  index=['row1', 'row2', 'row3'])

print(df)
#       col1 col2
# row1     1    a
# row2     2    x
# row3     3    あ

出力を見やすくするためにpprint、引数intoによる型指定の説明のためにOrderedDictをインポートしている。

なお、辞書ではなくJSON形式の文字列(str型)に変換したり、JSON形式のファイルとして出力(保存)したりしたい場合はto_json()メソッドを使う。以下の記事を参照。

pandas.DataFrameのto_dict()メソッド

pandas.DataFrameからto_dict()メソッドを呼び出すと、デフォルトでは以下のように辞書(dict型オブジェクト)に変換される。

d = df.to_dict()

pprint.pprint(d)
# {'col1': {'row1': 1, 'row2': 2, 'row3': 3},
#  'col2': {'row1': 'a', 'row2': 'x', 'row3': 'あ'}}

print(type(d))
# <class 'dict'>

辞書の形式を指定: 引数orient

引数orientによって、pandas.DataFrameの行ラベル(行名)index、列ラベル(列名)columns、値valuesをどのように辞書のkey, valueに割り当てるかの形式を指定できる。

dict

orient='dict'の場合、keyが列ラベル、valueが行ラベルと値の辞書となる。引数orientを省略した場合(デフォルト)はこの形式。

{column -> {index -> value}}
d_dict = df.to_dict(orient='dict')

pprint.pprint(d_dict)
# {'col1': {'row1': 1, 'row2': 2, 'row3': 3},
#  'col2': {'row1': 'a', 'row2': 'x', 'row3': 'あ'}}

print(d_dict['col1'])
# {'row1': 1, 'row2': 2, 'row3': 3}

print(type(d_dict['col1']))
# <class 'dict'>

list

orient='list'の場合、keyが列ラベル、valueが値のリストとなる。行名の情報は失われる。

{column -> [values]}
d_list = df.to_dict(orient='list')

pprint.pprint(d_list)
# {'col1': [1, 2, 3], 'col2': ['a', 'x', 'あ']}

print(d_list['col1'])
# [1, 2, 3]

print(type(d_list['col1']))
# <class 'list'>

series

orient='series'の場合、keyが列ラベル、valueが行ラベルと値のpandas.Seriesとなる。

{column -> Series(values)}
d_series = df.to_dict(orient='series')

pprint.pprint(d_series)
# {'col1': row1    1
# row2    2
# row3    3
# Name: col1, dtype: int64,
#  'col2': row1    a
# row2    x
# row3    あ
# Name: col2, dtype: object}

print(d_series['col1'])
# row1    1
# row2    2
# row3    3
# Name: col1, dtype: int64

print(type(d_series['col1']))
# <class 'pandas.core.series.Series'>

split

orient='split'の場合、key'index', 'columns', 'data'となり、それぞれのvalueが行ラベル、列ラベル、値のリストとなる。

{index -> [index], columns -> [columns], data -> [values]}
d_split = df.to_dict(orient='split')

pprint.pprint(d_split)
# {'columns': ['col1', 'col2'],
#  'data': [[1, 'a'], [2, 'x'], [3, 'あ']],
#  'index': ['row1', 'row2', 'row3']}

print(d_split['columns'])
# ['col1', 'col2']

print(type(d_split['columns']))
# <class 'list'>

records

orient='records'の場合、keyが列ラベル、valueが値となる辞書を要素とするリストとなる。行名の情報は失われる。

[{column -> value}, ... , {column -> value}]
l_records = df.to_dict(orient='records')

pprint.pprint(l_records)
# [{'col1': 1, 'col2': 'a'}, {'col1': 2, 'col2': 'x'}, {'col1': 3, 'col2': 'あ'}]

print(type(l_records))
# <class 'list'>

print(l_records[0])
# {'col1': 1, 'col2': 'a'}

print(type(l_records[0]))
# <class 'dict'>

index

orient='index'の場合、keyが行ラベル、valueが列ラベルと値の辞書となる。

{index -> {column -> value}}
d_index = df.to_dict(orient='index')

pprint.pprint(d_index)
# {'row1': {'col1': 1, 'col2': 'a'},
#  'row2': {'col1': 2, 'col2': 'x'},
#  'row3': {'col1': 3, 'col2': 'あ'}}

print(d_index['row1'])
# {'col1': 1, 'col2': 'a'}

print(type(d_index['row1']))
# <class 'dict'>

dict以外の型に変換: 引数into

引数intoに型を指定することで辞書(dict型)ではなくそのサブクラスであるOrderedDictなどに変換できる。

辞書の値valueに格納された辞書の型も指定した型になる。

od = df.to_dict(into=OrderedDict)

pprint.pprint(od)
# OrderedDict([('col1', OrderedDict([('row1', 1), ('row2', 2), ('row3', 3)])),
#              ('col2',
#               OrderedDict([('row1', 'a'), ('row2', 'x'), ('row3', 'あ')]))])

print(type(od))
# <class 'collections.OrderedDict'>

print(od['col1'])
# OrderedDict([('row1', 1), ('row2', 2), ('row3', 3)])

print(type(od['col1']))
# <class 'collections.OrderedDict'>

pandas.DataFrameの任意の2列から辞書生成

indexおよびデータ列から任意の2列を選んで辞書を生成することもできる。dict()zip()を利用する。

print(df.index)
# Index(['row1', 'row2', 'row3'], dtype='object')

print(df['col1'])
# row1    1
# row2    2
# row3    3
# Name: col1, dtype: int64

d_col = dict(zip(df.index, df['col1']))

print(d_col)
# {'row1': 1, 'row2': 2, 'row3': 3}

辞書を生成したあとでキーと値を入れ替えることも可能。以下の記事を参照。

あまり用途はないかもしれないが、行に対しても同様の処理が可能。

d_row = dict(zip(df.columns, df.loc['row1']))

print(d_row)
# {'col1': 1, 'col2': 'a'}

pandas.Seriesのto_dictメソッド

以下のpandas.Seriesを例とする。

print(df)
#       col1 col2
# row1     1    a
# row2     2    x
# row3     3    あ

s = df['col1']
print(s)
# row1    1
# row2    2
# row3    3
# Name: col1, dtype: int64

print(type(s))
# <class 'pandas.core.series.Series'>

pandas.Seriesto_dict()メソッドを呼ぶと、ラベルがキー、値がそのまま値となる辞書が生成される。

d = s.to_dict()
print(d)
# {'row1': 1, 'row2': 2, 'row3': 3}

print(type(d))
# <class 'dict'>

dict以外の型に変換: 引数into

pandas.Seriesto_dict()メソッドでも、引数intoに型を指定することで辞書(dict型)ではなくそのサブクラスであるOrderedDictなどに変換できる。

od = df['col1'].to_dict(OrderedDict)
print(od)
# OrderedDict([('row1', 1), ('row2', 2), ('row3', 3)])

print(type(od))
# <class 'collections.OrderedDict'>

関連カテゴリー

関連記事