Convert the DataFrame to a dictionary.
The type of the key-value pairs can be customized with the parameters (see below).
Determines the type of the values of the dictionary.
âdictâ (default) : dict like {column -> {index -> value}}
âlistâ : dict like {column -> [values]}
âseriesâ : dict like {column -> Series(values)}
âsplitâ : dict like {âindexâ -> [index], âcolumnsâ -> [columns], âdataâ -> [values]}
âtightâ : dict like {âindexâ -> [index], âcolumnsâ -> [columns], âdataâ -> [values], âindex_namesâ -> [index.names], âcolumn_namesâ -> [column.names]}
ârecordsâ : list like [{column -> value}, ⦠, {column -> value}]
âindexâ : dict like {index -> {column -> value}}
Added in version 1.4.0: âtightâ as an allowed value for the orient
argument
The collections.abc.MutableMapping subclass used for all Mappings in the return value. Can be the actual class or an empty instance of the mapping type you want. If you want a collections.defaultdict, you must pass it initialized.
Whether to include the index item (and index_names item if orient is âtightâ) in the returned dictionary. Can only be False
when orient is âsplitâ or âtightâ.
Added in version 2.0.0.
Return a collections.abc.MutableMapping object representing the DataFrame. The resulting transformation depends on the orient parameter.
Examples
>>> df = pd.DataFrame({'col1': [1, 2], ... 'col2': [0.5, 0.75]}, ... index=['row1', 'row2']) >>> df col1 col2 row1 1 0.50 row2 2 0.75 >>> df.to_dict() {'col1': {'row1': 1, 'row2': 2}, 'col2': {'row1': 0.5, 'row2': 0.75}}
You can specify the return orientation.
>>> df.to_dict('series') {'col1': row1 1 row2 2 Name: col1, dtype: int64, 'col2': row1 0.50 row2 0.75 Name: col2, dtype: float64}
>>> df.to_dict('split') {'index': ['row1', 'row2'], 'columns': ['col1', 'col2'], 'data': [[1, 0.5], [2, 0.75]]}
>>> df.to_dict('records') [{'col1': 1, 'col2': 0.5}, {'col1': 2, 'col2': 0.75}]
>>> df.to_dict('index') {'row1': {'col1': 1, 'col2': 0.5}, 'row2': {'col1': 2, 'col2': 0.75}}
>>> df.to_dict('tight') {'index': ['row1', 'row2'], 'columns': ['col1', 'col2'], 'data': [[1, 0.5], [2, 0.75]], 'index_names': [None], 'column_names': [None]}
You can also specify the mapping type.
>>> from collections import OrderedDict, defaultdict >>> df.to_dict(into=OrderedDict) OrderedDict([('col1', OrderedDict([('row1', 1), ('row2', 2)])), ('col2', OrderedDict([('row1', 0.5), ('row2', 0.75)]))])
If you want a defaultdict, you need to initialize it:
>>> dd = defaultdict(list) >>> df.to_dict('records', into=dd) [defaultdict(<class 'list'>, {'col1': 1, 'col2': 0.5}), defaultdict(<class 'list'>, {'col1': 2, 'col2': 0.75})]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4