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

  • 相关阅读:
    初涉Android蓝牙开发
    android真机调试方法
    BizTalk Server 系列文章目录
    【译文】ExtJS 4.1性能预览
    【译】ExtJS 4.1会带来什么
    cocos2dx 如何使用Visual Studio 2010和xcode 4混合编写手机游戏
    Mac osx 下让android 模拟器横屏
    c++ int convert to std::string 转换成std::string
    离ExtJS 4.1 beta发布只剩26个bug了
    Window.ShowModalDialog使用详解
  • 原文地址:https://www.cnblogs.com/Jaryer/p/14690267.html
Copyright © 2011-2022 走看看