Skip to content

dict

dict 是 Python 中的键值对,他和 DataFrame 的很多概念有些类似,因此他们之间的转换非常的方便。并且 dict 作为 Python 内置的格式能够被 Pyhton 世界的所有其他库使用。

orient

Pandas 中 orient 参数用于指定数据的格式或方向,控制着如何将 DataFrame 转换为 dict,orient 包含几种重要的格式:

  • dict: 默认,其中列名为键、列数据为值 -> {column: {index: value}}
Python
In [3]: df = pd.DataFrame({'col1': [1, 2],
   ...:                    'col2': [0.5, 0.75]},
   ...:                   index=['row1', 'row2'])

In [4]: df
Out[4]:
      col1  col2
row1     1  0.50
row2     2  0.75

In [5]: df.to_dict(orient='dict')
Out[5]: {'col1': {'row1': 1, 'row2': 2}, 'col2': {'row1': 0.5, 'row2': 0.75}}
  • list: 其中列名为键,所有列数据组成列表作为值 -> {column: [values]}
Python
In [6]: df.to_dict(orient='list')
Out[6]: {'col1': [1, 2], 'col2': [0.5, 0.75]}
  • series: 其中列名为键,值为 Series -> {column: Series(values)}
Python
In [7]: df.to_dict(orient='series')
Out[7]:
{'col1': row1    1
 row2    2
 Name: col1, dtype: int64,
 'col2': row1    0.50
 row2    0.75
 Name: col2, dtype: float64}
  • split: 生成具有 "index" "columns", "data" 三个键的字典,他们的值对应索引列表、列名列表和数据列表 -> {"index": [indexs], "columns": [columns], "data": [values]}
Python
In [8]: df.to_dict(orient='split')
Out[8]:
{'index': ['row1', 'row2'],
 'columns': ['col1', 'col2'],
 'data': [[1, 0.5], [2, 0.75]]}
  • index: 对应 {index: {column: value}}
Python
In [9]: df.to_dict(orient='index')
Out[9]: {'row1': {'col1': 1, 'col2': 0.5}, 'row2': {'col1': 2, 'col2': 0.75}}
  • records: 最为特殊的也最为常用的一种方式,他返回一个列表,其中抛弃了 index 列表中的值是列名到值 -> [{column: value} ....]
Python
In [10]: df.to_dict(orient='records')
Out[10]: [{'col1': 1, 'col2': 0.5}, {'col1': 2, 'col2': 0.75}]
  • tight: 有点类似 split -> {"index": [indexs], "columns": [columns], "data": [values], "index_names": [index.names], "column_names": [column.names]}
Python
In [11]: df.to_dict(orient='tight')
Out[11]:
{'index': ['row1', 'row2'],
 'columns': ['col1', 'col2'],
 'data': [[1, 0.5], [2, 0.75]],
 'index_names': [None],
 'column_names': [None]}

to_dict

to_dict和核心就是 orident 参数:

Python
def to_dict(
    orident='dict',
):
    pass

from_dict

from_dict从字典中构建 DataFrame,他的核心同样是 orient 参数,只不过他只接受三种值:

  • columns: 将 data 的键作为 columns 来构造 DataFrame
  • index: 将 data 的键作为 index 来构造 DataFrame
  • tight: 等同于上面的 tight,即要求 data 必须包含 ["index", "columns", "data", "index_names", "column_names"] 这五个键
Python
def from_dict(
    data: dict, # 数据的格式除了 tight 外要求 {index|column: [values] ...} 并且 values 的长度必须保持一致
    orient='columns'
    columns:list # 只能配合 orient='index' 使用
):
    pass
Python
In [12]: data = {'key1': [3,2,1,0], 'key2': [0,1,2,3]}

In [13]: pd.DataFrame.from_dict(data)
Out[13]:
   key1  key2
0     3     0
1     2     1
2     1     2
3     0     3

# index 还可以指定 columns
In [14]: pd.DataFrame.from_dict(data, orient='index')
Out[14]:
      0  1  2  3
key1  3  2  1  0
key2  0  1  2  3