- {‘a’: {0: ‘red’, 1: ‘yellow’, 2: ‘blue’},
- ‘b’: {0: 0.5, 1: 0.25, 2: 0.125}}
- {‘a’: [‘red’, ‘yellow’, ‘blue’],
- ‘b’: [0.5, 0.25, 0.125]}
- {‘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}
- {‘columns’: [‘a’, ‘b’],
- ‘data’: [[‘red’, 0.5], [‘yellow’, 0.25], [‘blue’, 0.125]],
- ‘index’: [0, 1, 2]}
- [{‘a’: ‘red’, ‘b’: 0.5},
- {‘a’: ‘yellow’, ‘b’: 0.25},
- {‘a’: ‘blue’, ‘b’: 0.125}]
- {0: {‘a’: ‘red’, ‘b’: 0.5},
- 1: {‘a’: ‘yellow’, ‘b’: 0.25},
- 2: {‘a’: ‘blue’, ‘b’: 0.125}}
import pandas as pd
df = pd.DataFrame([['red', 0.5], ['yellow', 0.25], ['blue', 0.125]], columns=['a', 'b'])
# 或
df = pd.DataFrame(pd.DataFrame({'a': ['red', 'yellow', 'blue'], 'b': [0.5, 0.25, 0.125]}))
print(df)
# color value
# 0 red 0.500
# 1 yellow 0.250
# 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}}
```