|
64 | 64 | _values_from_object,
|
65 | 65 | _maybe_box_datetimelike,
|
66 | 66 | _dict_compat,
|
67 |
| - _standardize_mapping) |
| 67 | + prep_maping_for_to_dict) |
68 | 68 | from pandas.core.generic import NDFrame, _shared_docs
|
69 | 69 | from pandas.core.index import Index, MultiIndex, _ensure_index
|
70 | 70 | from pandas.core.indexing import (maybe_droplevels, convert_to_index_sliceable,
|
@@ -889,19 +889,59 @@ def to_dict(self, orient='dict', into=dict):
|
889 | 889 | instance of the mapping type you want. If you want a
|
890 | 890 | collections.defaultdict, you must pass an initialized
|
891 | 891 | instance.
|
| 892 | + |
892 | 893 | .. versionadded:: 0.21.0
|
893 | 894 |
|
894 | 895 | Returns
|
895 | 896 | -------
|
896 | 897 | result : collections.Mapping like {column -> {index -> value}}
|
897 | 898 | If ``into`` is collections.defaultdict, the return
|
898 | 899 | value's default_factory will be None.
|
| 900 | + |
| 901 | + Examples |
| 902 | + -------- |
| 903 | + >>> from pandas import DataFrame |
| 904 | + >>> from collections import OrderedDict, defaultdict |
| 905 | + >>> df = DataFrame({'col1': [1, 2], 'col2': [0.5, 0.75]}, index=['a', 'b']) |
| 906 | + >>> df |
| 907 | + col1 col2 |
| 908 | + a 1 0.1 |
| 909 | + b 2 0.2 |
| 910 | + >>> df.to_dict() |
| 911 | + {'col1': {'a': 1, 'b': 2}, 'col2': {'a': 0.5, 'b': 0.75}} |
| 912 | + |
| 913 | + You can specify the return orientation. |
| 914 | + |
| 915 | + >>> df.to_dict('series') |
| 916 | + {'col1': a 1 |
| 917 | + b 2 |
| 918 | + Name: col1, dtype: int64, 'col2': a 0.50 |
| 919 | + b 0.75 |
| 920 | + Name: col2, dtype: float64} |
| 921 | + >>> df.to_dict('split') |
| 922 | + {'columns': ['col1', 'col2'], |
| 923 | + 'data': [[1.0, 0.5], [2.0, 0.75]], |
| 924 | + 'index': ['a', 'b']} |
| 925 | + >>> df.to_dict('records') |
| 926 | + [{'col1': 1.0, 'col2': 0.5}, {'col1': 2.0, 'col2': 0.75}] |
| 927 | + >>> df.to_dict('index') |
| 928 | + {'a': {'col1': 1.0, 'col2': 0.5}, 'b': {'col1': 2.0, 'col2': 0.75}} |
| 929 | + |
| 930 | + You can also specify the mapping type. |
| 931 | + |
| 932 | + >>> df.to_dict(into=OrderedDict) |
| 933 | + OrderedDict([('col2', OrderedDict([('a', 0.5), ('b', 0.75)])), |
| 934 | + ('col1', OrderedDict([('a', 1), ('b', 2)]))]) |
| 935 | + >>> dd = defaultdict(list) |
| 936 | + >>> df.to_dict('records', into=dd) |
| 937 | + [defaultdict(list, {'col1': 1.0, 'col2': 0.5}), |
| 938 | + defaultdict(list, {'col1': 2.0, 'col2': 0.75})] |
899 | 939 | """
|
900 | 940 | if not self.columns.is_unique:
|
901 | 941 | warnings.warn("DataFrame columns are not unique, some "
|
902 | 942 | "columns will be omitted.", UserWarning)
|
903 | 943 | # GH16122
|
904 |
| - into_c = _standardize_mapping(into) |
| 944 | + into_c = prep_maping_for_to_dict(into) |
905 | 945 | if orient.lower().startswith('d'):
|
906 | 946 | return into_c(
|
907 | 947 | (k, v.to_dict(into)) for k, v in compat.iteritems(self))
|
|
0 commit comments