pandas.DataFrame.to_dict()的使用详解

将df转为字典时的用法

  • 以下基于windows10, python3.6环境通过验证
In [1]: import pandas as pd

In [2]: import numpy as np

In [3]: df = pd.DataFrame({'colA' : list('AABCA'), 'colB' : ['X',np.nan,'Ya','Xb','Xa'],'colC' : [100,50,30,5
   ...: 0,20], 'colD': [90,60,60,80,50]})

In [4]: df
Out[4]:
  colA colB  colC  colD
0    A    X   100    90
1    A  NaN    50    60
2    B   Ya    30    60
3    C   Xb    50    80
4    A   Xa    20    50

In [5]: df.to_dict(orient='dict')
Out[5]:
{'colA': {0: 'A', 1: 'A', 2: 'B', 3: 'C', 4: 'A'},
 'colB': {0: 'X', 1: nan, 2: 'Ya', 3: 'Xb', 4: 'Xa'},
 'colC': {0: 100, 1: 50, 2: 30, 3: 50, 4: 20},
 'colD': {0: 90, 1: 60, 2: 60, 3: 80, 4: 50}}

In [6]: df.to_dict(orient='list')
Out[6]:
{'colA': ['A', 'A', 'B', 'C', 'A'],
 'colB': ['X', nan, 'Ya', 'Xb', 'Xa'],
 'colC': [100, 50, 30, 50, 20],
 'colD': [90, 60, 60, 80, 50]

In [7]: df.to_dict(orient='series')
Out[7]:
{'colA': 0    A
 1    A
 2    B
 3    C
 4    A
 Name: colA, dtype: object, 'colB': 0      X
 1    NaN
 2     Ya
 3     Xb
 4     Xa
 Name: colB, dtype: object, 'colC': 0    100
 1     50
 2     30
 3     50
 4     20
 Name: colC, dtype: int64, 'colD': 0    90
 1    60
 2    60
 3    80
 4    50
 Name: colD, dtype: int64}

In [8]: df.to_dict(orient='split')
Out[8]:
{'columns': ['colA', 'colB', 'colC', 'colD'],
 'data': [['A', 'X', 100, 90],
  ['A', nan, 50, 60],
  ['B', 'Ya', 30, 60],
  ['C', 'Xb', 50, 80],
  ['A', 'Xa', 20, 50]],
 'index': [0, 1, 2, 3, 4]}

In [9]: df.to_dict(orient='records')
Out[9]:
[{'colA': 'A', 'colB': 'X', 'colC': 100, 'colD': 90},
 {'colA': 'A', 'colB': nan, 'colC': 50, 'colD': 60},
 {'colA': 'B', 'colB': 'Ya', 'colC': 30, 'colD': 60},
 {'colA': 'C', 'colB': 'Xb', 'colC': 50, 'colD': 80},
 {'colA': 'A', 'colB': 'Xa', 'colC': 20, 'colD': 50}]

In [10]: df.to_dict(orient='index')
Out[10]:
{0: {'colA': 'A', 'colB': 'X', 'colC': 100, 'colD': 90},
 1: {'colA': 'A', 'colB': nan, 'colC': 50, 'colD': 60},
 2: {'colA': 'B', 'colB': 'Ya', 'colC': 30, 'colD': 60},
 3: {'colA': 'C', 'colB': 'Xb', 'colC': 50, 'colD': 80},
 4: {'colA': 'A', 'colB': 'Xa', 'colC': 20, 'colD': 50}}

你可能感兴趣的:(python.pandas,进阶)