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,我们一般都不需要去设定这个值。

  • 相关阅读:
    SQL SERVER 2008的数据压缩
    protected,internal和protected internal
    CSS笔记
    太吓人了!妈妈必看:国内人贩子抢孩子竟使出狠招
    ASP.NET上传图片的简单方法
    VS2005快捷键大全
    判断ExecuteScalar()是否返回结果
    AppSettings和ConnectionStrings的区别
    VSS中的签入和签出
    对目前工作烦躁的人来看看,你真正明白多少
  • 原文地址:https://www.cnblogs.com/Jaryer/p/14690267.html
Copyright © 2011-2022 走看看