zoukankan      html  css  js  c++  java
  • pandas to 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,我们一般都不需要去设定这个值。

  • 相关阅读:
    java三大框架
    Servlet 工作原理解析
    Android四大基本组件介绍与生命周期
    wait 和 sleep
    Linux Mysql使用
    Android开发人员必备的10 个开发工具
    AIDL
    IPC Binder
    php 比较2字符串相似度 百分比
    php 数字 的简单加解密
  • 原文地址:https://www.cnblogs.com/Jaryer/p/14690267.html
Copyright © 2011-2022 走看看