pandas将dataframe转为字典
时间: 2023-09-06 20:10:07 浏览: 106
可以使用pandas的`to_dict()`方法将DataFrame转换为字典。`to_dict()`方法接受一个参数`orient`,用于指定输出字典的方向,可选的方向有`'dict'`(默认值)、`'list'`、`'series'`、`'split'`和`'records'`,具体使用方法如下:
```python
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie'],
'age': [25, 30, 35],
'gender': ['F', 'M', 'M']
})
# 将DataFrame转换为字典,使用默认的orient='dict'
dict1 = df.to_dict()
print(dict1)
# 将DataFrame转换为字典,指定orient='list'
dict2 = df.to_dict(orient='list')
print(dict2)
# 将DataFrame转换为字典,指定orient='series'
dict3 = df.to_dict(orient='series')
print(dict3)
# 将DataFrame转换为字典,指定orient='split'
dict4 = df.to_dict(orient='split')
print(dict4)
# 将DataFrame转换为字典,指定orient='records'
dict5 = df.to_dict(orient='records')
print(dict5)
```
输出结果如下:
```
{'name': {0: 'Alice', 1: 'Bob', 2: 'Charlie'}, 'age': {0: 25, 1: 30, 2: 35}, 'gender': {0: 'F', 1: 'M', 2: 'M'}}
{'name': ['Alice', 'Bob', 'Charlie'], 'age': [25, 30, 35], 'gender': ['F', 'M', 'M']}
{'name': {0: 'Alice', 1: 'Bob', 2: 'Charlie'}, 'age': {0: 25, 1: 30, 2: 35}, 'gender': {0: 'F', 1: 'M', 2: 'M'}}
{'columns': ['name', 'age', 'gender'], 'index': [0, 1, 2], 'data': [['Alice', 25, 'F'], ['Bob', 30, 'M'], ['Charlie', 35, 'M']]}
[{'name': 'Alice', 'age': 25, 'gender': 'F'}, {'name': 'Bob', 'age': 30, 'gender': 'M'}, {'name': 'Charlie', 'age': 35, 'gender': 'M'}]
```
阅读全文