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

  • 相关阅读:
    4-数组、指针与字符串1.3-this指针
    Linux命令----cp
    Linux命令----mv
    Linux命令----rm
    PHP7下的协程实现 转
    php生成器 yield 转
    python并发编程之多进程(实践篇) 转
    python 多进程
    线程创建 线程数
    多任务 执行
  • 原文地址:https://www.cnblogs.com/Jaryer/p/14690267.html
Copyright © 2011-2022 走看看