pandas to_dict函数的用法介绍

本文介绍了pandas.core.frame.DataFrame模块中的to_dict方法,该方法可选择六种转换类型,对应参数'dict'、'list'等。文中详细说明了各参数的含义,并通过具体示例展示了不同关键字参数(如orient='series'等)及指定映射类型时to_dict方法的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、to_dict 在pandas.core.frame.DataFrame模块中

可以选择六种的转换类型,分别对应于参数 ‘dict’, ‘list’, ‘series’, ‘split’, ‘records’, ‘index’,下面逐一介绍每种的用法

 

>>> help(pandas.core.frame.DataFrame.to_dict)
Help on function to_dict in module pandas.core.frame:

to_dict(self, orient='dict', into=<class '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.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.

        .. versionadded:: 0.21.0

    Returns
    -------
    result : collections.Mapping like {column -> {index -> value}}

    See Also
    --------
    DataFrame.from_dict: create a DataFrame from a dictionary
    DataFrame.to_json: convert a DataFrame to JSON format

2、举例说明   

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

    You can specify the return orientation.

1)、关键字参数orient=’series’    

>>> df.to_dict('series')
    {'col1': a    1
             b    2
             Name: col1, dtype: int64,
     'col2': a    0.50
             b    0.75
             Name: col2, dtype: float64}

2)、关键字参数orient=’split    

    >>> df.to_dict('split')
    {'index': ['a', 'b'], 'columns': ['col1', 'col2'],
     'data': [[1.0, 0.5], [2.0, 0.75]]}

3)、关键字参数orient=’records    

    >>> df.to_dict('records')
    [{'col1': 1.0, 'col2': 0.5}, {'col1': 2.0, 'col2': 0.75}]

4)、关键字参数orient=’index    

    >>> df.to_dict('index')
    {'a': {'col1': 1.0, 'col2': 0.5}, 'b': {'col1': 2.0, 'col2': 0.75}}

5)、关键字参数orient=’dict  

df_dict=df.to_dict('dict')
df_dict

{'col1': {'a': 1, 'b': 2}, 'col2': {'a': 0.5, 'b': 0.75}}

6)、关键字参数orient=’list  

df_list=df.to_dict('list')
df_list

{'col1': [1, 2], 'col2': [0.5, 0.75]}

如果调用可以用 df_list['col1'][1]

 

    You can also specify the mapping type.

    >>> from collections import OrderedDict, defaultdict
    >>> df.to_dict(into=OrderedDict)
    OrderedDict([('col1', OrderedDict([('a', 1), ('b', 2)])),
                 ('col2', OrderedDict([('a', 0.5), ('b', 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.0, 'col2': 0.5}),
     defaultdict(<class 'list'>, {'col1': 2.0, 'col2': 0.75})]

 

pandas to_dict 的用法 https://blog.youkuaiyun.com/m0_37804518/article/details/78444110 

 

 

### Pandas `pd.to_dict` 使用方法及数据结构转换详解 Pandas 提供了强大的工具来处理和转换数据结构,其中之一就是 `to_dict()` 方法。该方法可以将 DataFrame 转换为字典形式,支持多种不同的输出格式以满足不同需求。 #### 参数说明 `DataFrame.to_dict(orient='dict', into=<class 'dict'>)` 是主要接口[^4]。参数解释如下: - **orient**: 字符串值,指定输出字典的形式。可选值有 `"dict"`、`"list"`、`"series"`、`"split"`、`"records"` 和 `"index"`。 - **into**: 默认为 `<class 'dict'>`,用于指定返回对象的具体类型(通常不需要修改)。 以下是各模式下具体的输出样式及其适用场景: --- #### 示例代码与解析 ```python import pandas as pd # 构建示例 DataFrame df = pd.DataFrame({ 'A': ['foo', 'bar'], 'B': [1, 2], 'C': [3.5, 4.2] }) ``` | A | B | C | |-----|----|-----| | foo | 1 | 3.5 | | bar | 2 | 4.2 | ##### 1. orient="dict" 在这种模式下,每一列被转化为一个字典,键是索引标签,值是对应的单元格内容。 ```python result = df.to_dict(orient="dict") print(result) ``` 输出结果: ```plaintext {'A': {0: 'foo', 1: 'bar'}, 'B': {0: 1, 1: 2}, 'C': {0: 3.5, 1: 4.2}} ``` 适用于需要按列访问数据的情况。 --- ##### 2. orient="list" 在此模式下,每一列被转化为一个列表,顺序保持不变。 ```python result = df.to_dict(orient="list") print(result) ``` 输出结果: ```plaintext {'A': ['foo', 'bar'], 'B': [1, 2], 'C': [3.5, 4.2]} ``` 适合批量读取整列数据的场合。 --- ##### 3. orient="series" 这种模式会将每一列视为独立的 Series,并将其转为字典。 ```python result = df.to_dict(orient="series") print(result) ``` 输出结果: ```plaintext {'A': 0 foo 1 bar Name: A, dtype: object, 'B': 0 1 1 2 Name: B, dtype: int64, 'C': 0 3.5 1 4.2 Name: C, dtype: float64} ``` 主要用于涉及复杂序列操作的任务。 --- ##### 4. orient="split" 此模式将 DataFrame 拆分为三个部分:索引 (`index`)、列名 (`columns`) 和实际数据 (`data`)。 ```python result = df.to_dict(orient="split") print(result) ``` 输出结果: ```plaintext { 'index': [0, 1], 'columns': ['A', 'B', 'C'], 'data': [['foo', 1, 3.5], ['bar', 2, 4.2]] } ``` 非常适合保存或传输完整的 DataFrame 结构信息。 --- ##### 5. orient="records" 每行会被单独作为一个字典记录下来。 ```python result = df.to_dict(orient="records") print(result) ``` 输出结果: ```plaintext [ {'A': 'foo', 'B': 1, 'C': 3.5}, {'A': 'bar', 'B': 2, 'C': 4.2} ] ``` 常用于 JSON 格式化或其他外部系统的交互。 --- ##### 6. orient="index" 以行为单位构建字典,其中外层键代表原始索引,内层键对应列名。 ```python result = df.to_dict(orient="index") print(result) ``` 输出结果: ```plaintext { 0: {'A': 'foo', 'B': 1, 'C': 3.5}, 1: {'A': 'bar', 'B': 2, 'C': 4.2} } ``` 特别适合作为某些机器学习库输入时的数据准备阶段。 --- ### 总结 以上展示了 `to_dict()` 函数的不同使用方式以及各自的特点。选择合适的 `orient` 值取决于目标应用场景和后续处理逻辑的要求[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值