pandas——to_dict使用详解

原文:https://blog.****.net/weixin_39791387/article/details/87627235

 

将df转为字典时的用法

  • 以下基于windows10, python3.6环境通过验证
 1 In [1]: import pandas as pd
 2 
 3 In [2]: import numpy as np
 4 
 5 In [3]: df = pd.DataFrame({'colA' : list('AABCA'), 'colB' : ['X',np.nan,'Ya','Xb','Xa'],'colC' : [100,50,30,5
 6    ...: 0,20], 'colD': [90,60,60,80,50]})
 7 
 8 In [4]: df
 9 Out[4]:
10   colA colB  colC  colD
11 0    A    X   100    90
12 1    A  NaN    50    60
13 2    B   Ya    30    60
14 3    C   Xb    50    80
15 4    A   Xa    20    50
16 
17 In [5]: df.to_dict(orient='dict')
18 Out[5]:
19 {'colA': {0: 'A', 1: 'A', 2: 'B', 3: 'C', 4: 'A'},
20  'colB': {0: 'X', 1: nan, 2: 'Ya', 3: 'Xb', 4: 'Xa'},
21  'colC': {0: 100, 1: 50, 2: 30, 3: 50, 4: 20},
22  'colD': {0: 90, 1: 60, 2: 60, 3: 80, 4: 50}}
23 
24 In [6]: df.to_dict(orient='list')
25 Out[6]:
26 {'colA': ['A', 'A', 'B', 'C', 'A'],
27  'colB': ['X', nan, 'Ya', 'Xb', 'Xa'],
28  'colC': [100, 50, 30, 50, 20],
29  'colD': [90, 60, 60, 80, 50]
30 
31 In [7]: df.to_dict(orient='series')
32 Out[7]:
33 {'colA': 0    A
34  1    A
35  2    B
36  3    C
37  4    A
38  Name: colA, dtype: object, 'colB': 0      X
39  1    NaN
40  2     Ya
41  3     Xb
42  4     Xa
43  Name: colB, dtype: object, 'colC': 0    100
44  1     50
45  2     30
46  3     50
47  4     20
48  Name: colC, dtype: int64, 'colD': 0    90
49  1    60
50  2    60
51  3    80
52  4    50
53  Name: colD, dtype: int64}
54 
55 In [8]: df.to_dict(orient='split')
56 Out[8]:
57 {'columns': ['colA', 'colB', 'colC', 'colD'],
58  'data': [['A', 'X', 100, 90],
59   ['A', nan, 50, 60],
60   ['B', 'Ya', 30, 60],
61   ['C', 'Xb', 50, 80],
62   ['A', 'Xa', 20, 50]],
63  'index': [0, 1, 2, 3, 4]}
64 
65 In [9]: df.to_dict(orient='records')
66 Out[9]:
67 [{'colA': 'A', 'colB': 'X', 'colC': 100, 'colD': 90},
68  {'colA': 'A', 'colB': nan, 'colC': 50, 'colD': 60},
69  {'colA': 'B', 'colB': 'Ya', 'colC': 30, 'colD': 60},
70  {'colA': 'C', 'colB': 'Xb', 'colC': 50, 'colD': 80},
71  {'colA': 'A', 'colB': 'Xa', 'colC': 20, 'colD': 50}]
72 
73 In [10]: df.to_dict(orient='index')
74 Out[10]:
75 {0: {'colA': 'A', 'colB': 'X', 'colC': 100, 'colD': 90},
76  1: {'colA': 'A', 'colB': nan, 'colC': 50, 'colD': 60},
77  2: {'colA': 'B', 'colB': 'Ya', 'colC': 30, 'colD': 60},
78  3: {'colA': 'C', 'colB': 'Xb', 'colC': 50, 'colD': 80},
79  4: {'colA': 'A', 'colB': 'Xa', 'colC': 20, 'colD': 50}}

 

上一篇:隐马尔科夫模型-前向算法


下一篇:查询最占资源、CPU、内存、和执行最长的SQL语句