一、dataframe.to_dict()
这是 pandas 库中的一个方法,用于将 dataframe 对象转换为字典。这个方法非常有用,特别是在需要将 dataframe 的数据结构转换为 json 格式或其他与字典兼容的格式时。
参数:
to_dict() 方法有几个参数可选,用于控制输出的格式。
- orient:指定字典格式。默认为 'dict' ,表示每一列一个键。
- to_dict('records'):返回一个字典列表,每个字典代表一行记录,键是列名,值是数据。
- to_dict('index'):返回一个字典,其中索引作为键,列名作为子键。
- to_dict('series'):类似 'records',但返回的是一个列表,其中每个元素是一个字典。
- to_dict('split'):返回一个字典,包含两个键:'index' 和 'columns',它们分别映射到索引和列名的列表,值是数据。
- to_dict('long'):将 dataframe 转换为长格式字典。
二、举例
创建一个 dataframe
import pandas as pd df = pd.dataframe({ 'column1': [1, 2], 'column2': ['a', 'b'] })
to_dict('records')
dic = df.to_dict('records') print(dic) # >>> dic[1] print(dic[1]) # >>> dic[1]['column1'] print(dic[1]['column1'])
[{'column1': 1, 'column2': 'a'}, {'column1': 2, 'column2': 'b'}]
>>> dic[1]{'column1': 2, 'column2': 'b'}
>>> dic[1]['column1']2
to_dict('list')
lis = df.to_dict('list') print(list) # >>> list['column1'] print(list['column1'])
{'column1': [1, 2], 'column2': ['a', 'b']}
>>> list['column1'][1, 2]
to_dict('series')
ser= df.to_dict('series') print(ser) # >>> series['column1'] print(ser['column1'])
{'column1': 0 1
1 2
name: column1, dtype: int64, 'column2': 0 a
1 b
name: column2, dtype: object}
>>> series['column1']:0 1
1 2
name: column1, dtype: int64
to_dict('index')
ind = df.to_dict('index') print(ind) # >>> index[1] print(ind[1]) # >>> index[1]['column1'] print(ind[1]['column1'])
{0: {'column1': 1, 'column2': 'a'}, 1: {'column1': 2, 'column2': 'b'}}
>>> index[1]:{'column1': 2, 'column2': 'b'}
>>> index[1]['column1']2
到此这篇关于pandas中dataframe.to_dict()的文章就介绍到这了,更多相关pandas中dataframe.to_dict()内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论