数据处理中经常需要将pandas中的DataFrame类型转dict类型
常用的格式主要有以下三种
转成一个dict,keys是df的columns,values是一个带index的dict
import pandas as pd
df = pd.DataFrame({"name":["a","b","c"],"score":[2,3,5]})
df.to_dict(orient="dict")
{‘name’: {0: ‘a’, 1: ‘b’, 2: ‘c’}, ‘score’: {0: 2, 1: 3, 2: 5}}
转成一个list,每个元素是一个dict
import pandas as pd
df = pd.DataFrame({"name":["a","b","c"],"score":[2,3,5]})
df.to_dict(orient="record")
[{‘name’: ‘a’, ‘score’: 2},
{‘name’: ‘b’, ‘score’: 3},
{‘name’: ‘c’, ‘score’: 5}]
转成一个dict,keys是df的columns,values是list
import pandas as pd
df = pd.DataFrame({"name":["a","b","c"],"score":[2,3,5]})
df.to_dict(orient="list")
{‘name’: [‘a’, ‘b’, ‘c’], ‘score’: [2, 3, 5]}