1. import pandas as pd
  2. df = pd.DataFrame([['red', 0.5], ['yellow', 0.25], ['blue', 0.125]], columns=['a', 'b'])
  3. # 或
  4. df = pd.DataFrame(pd.DataFrame({'a': ['red', 'yellow', 'blue'], 'b': [0.5, 0.25, 0.125]}))
  5. print(df)
  6. # color value
  7. # 0 red 0.500
  8. # 1 yellow 0.250
  9. # 2 blue 0.125

使用 **df.to_dict([参数])** 函数,参数有以下值:

  • ‘dict’:键——列名,值——(键——索引,值——列值)
  • ‘list’:键——列名,值——列值列表
  • ‘series’:与 ‘list’ 类似,但返回对象不同
  • ‘split’:返回 列名、数据、索引三个键值对的字典
  • ‘records’:将每行转成字典,键——列名,值——列值,最后字典组成一个列表
  • ‘index’:键——索引,值——(键——列名,值——列值) ```python

    df.to_dict(‘dict’)

    {‘a’: {0: ‘red’, 1: ‘yellow’, 2: ‘blue’},

    ‘b’: {0: 0.5, 1: 0.25, 2: 0.125}}

df.to_dict(‘list’)

{‘a’: [‘red’, ‘yellow’, ‘blue’],

‘b’: [0.5, 0.25, 0.125]}

df.to_dict(‘series’)

{‘a’: 0 red

1 yellow

2 blue

Name: a, dtype: object,

‘b’: 0 0.500

1 0.250

2 0.125

Name: b, dtype: float64}

df.to_dict(‘split’)

{‘columns’: [‘a’, ‘b’],

‘data’: [[‘red’, 0.5], [‘yellow’, 0.25], [‘blue’, 0.125]],

‘index’: [0, 1, 2]}

df.to_dict(‘records’)

[{‘a’: ‘red’, ‘b’: 0.5},

{‘a’: ‘yellow’, ‘b’: 0.25},

{‘a’: ‘blue’, ‘b’: 0.125}]

df.to_dict(‘index’)

{0: {‘a’: ‘red’, ‘b’: 0.5},

1: {‘a’: ‘yellow’, ‘b’: 0.25},

2: {‘a’: ‘blue’, ‘b’: 0.125}}

```