• pandas 中 to_dict 的用法


    DataFrame.to_dict(orient='dict'into=<class 'dict'>)

    参数:
    orient str {‘dict’, ‘list’, ‘series’, ‘split’, ‘records’, ‘index’}

     

    • ‘dict’ (default) : {column -> {index -> value}}
    • ‘list’ :  {column -> [values]}
    • ‘series’ : {column -> Series(values)}
    • ‘split’ : {‘index’ -> [index], ‘columns’ -> [columns], ‘data’ -> [values]}
    • ‘records’ : [{column -> value}, … , {column -> value}]
    • ‘index’ : {index -> {column -> value}}

    也可以用缩写表示,  s 代表 series ,sp 代表 split.

    into class, 默认dict
    Returns:
    dict, list 或 collections.Mapping

     

    例子:

    >>> df = pd.DataFrame({'col1': [1, 2],
    ...                    'col2': [0.5, 0.75]},
    ...                   index=['row1', 'row2'])
    >>> df
          col1  col2
    row1     1  0.50
    row2     2  0.75
    >>> df.to_dict()
    {'col1': {'row1': 1, 'row2': 2}, 'col2': {'row1': 0.5, 'row2': 0.75}}

    可以指定返回的类型
    >>> df.to_dict('series')
    {'col1': row1    1
             row2    2
    Name: col1, dtype: int64,
    'col2': row1    0.50
            row2    0.75
    Name: col2, dtype: float64}
    
    >>> df.to_dict('split')
    {'index': ['row1', 'row2'], 'columns': ['col1', 'col2'],
     'data': [[1, 0.5], [2, 0.75]]}
    
    >>> df.to_dict('records')
    [{'col1': 1, 'col2': 0.5}, {'col1': 2, 'col2': 0.75}]
    
    >>> df.to_dict('index')
    {'row1': {'col1': 1, 'col2': 0.5}, 'row2': {'col1': 2, 'col2': 0.75}}
    

    >>> from collections import OrderedDict, defaultdict >>> df.to_dict(into=OrderedDict) OrderedDict([('col1', OrderedDict([('row1', 1), ('row2', 2)])), ('col2', OrderedDict([('row1', 0.5), ('row2', 0.75)]))])

    If you want a defaultdict, you need to initialize it:

    >>> dd = defaultdict(list)
    >>> df.to_dict('records', into=dd)
    [defaultdict(<class 'list'>, {'col1': 1, 'col2': 0.5}),
     defaultdict(<class 'list'>, {'col1': 2, 'col2': 0.75})]
  • 相关阅读:
    二分法检索数组
    Linux安装CDH
    myeclipse操作hdfs
    Linux安装hbase
    Linux安装zookeeper
    Linux安装msql
    fluem全分布环境搭建
    bash: jps: 未找到命令...
    自动化项目Jenkins持续集成
    linux卸载mysql====安装新的虚拟机 自带的基本都要卸载!? mysql tomcat java Python可以不用卸载
  • 原文地址:https://www.cnblogs.com/liyun1/p/10957107.html
Copyright © 2020-2023  润新知