pandas 将dataframe 转换为 dict

将pandas 数据转换为 dict

这里将pandas 的dataframe 转化为 dict 使用的是 to_dict() 方法

这里放一部分源码:

def to_dict(self, orient="dict", into=dict):
Convert the DataFrame to a dictionary.

        The type of the key-value pairs can be customized with the parameters
        (see below).

        Parameters
        ----------
        orient : str {'dict', 'list', 'series', 'split', 'records', 'index'}
            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]}
            - 'records' : list like
              [{column -> value}, ... , {column -> value}]
            - 'index' : dict like {index -> {column -> value}}

            Abbreviations are allowed. `s` indicates `series` and `sp`
            indicates `split`.

        into : class, default dict
            The collections.abc.Mapping 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.

        Returns
        -------
        dict, list or collections.abc.Mapping
            Return a collections.abc.Mapping object representing the DataFrame.
            The resulting transformation depends on the `orient` parameter.

可以看到 to_dict 有两个参数,一个是 orient,另一个是 into

orient 参数

orient 参数设定的是字典的值类型,该参数可选的值有:

- '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]}
- 'records' : list like [{column -> value}, ... , {column -> value}]
- 'index' : dict like {index -> {column -> value}}

设定不同的参数值,可以转换为不同类型的字典

into 参数

into 参数用于设定所有映射的collections.abc.Mapping子类

在返回值中,可以是您想要的映射类型的实际类或空实例

如果你想要一个collections.defaultdict,你必须将它初始化。

这个参数的默认是dict,我们一般都不需要去设定这个值。

posted @ 2021-04-22 16:29  JunCode  阅读(1100)  评论(0编辑  收藏  举报