在工作中,使用pandas时,常常需要将dataframe中的数据按照指定的格式输出给下游使用,很多时候,下游指定的格式并不是很特别,而是比较常见的,这时,我们就不需要自己专门定义方法去处理了,可以先看一下有没有现成的方法可以调用,会节省我们很多时间,提高我们程序的效率。
下面我介绍一下dataframe的一个格式化输出的方法,to_dict()
1、 使用默认的to_dict()格式化输出
df = pd.DataFrame({'col1': [1, 2],
'col2': [0.5, 0.75]},
index=['row1', 'row2'])
df
Out[3]:
col1 col2
row1 1 0.50
row2 2 0.75
df.to_dict()
Out[4]: {'col1': {'row1': 1, 'row2': 2}, 'col2': {'row1': 0.5, 'row2': 0.75}}
默认情况下输出时,会是dict类型,key为列名,值也是dict类型,每一个key对应 index,值为对应行列具体值。
1.1、指定series输出
df.to_dict('series')
Out[5]:
{'col1':
row1 1
row2 2
Name: col1, dtype: int64,
'col2':
row1 0.50
row2 0.75
Name: col2, dtype: float64}
指定series参数时,输出仍为dict,并且key仍为列名, 但是 对应的value是Series类型了
1.2 指定split输出
df.to_dict('split')
Out[6]:
{'index': ['row1', 'row2'],
'columns': ['col1', 'col2'],
'data': [[1, 0.5], [2, 0.75]]}
指定split参数时,输出仍为dict。这时是将df的各个部分分开输出, value为列表类型, data对应的是二维数组。
1.3 指定record输出
df.to_dict('records')
Out[7]: [{'col1': 1, 'col2': 0.5}, {'col1': 2, 'col2': 0.75}]
指定records时,丢弃了index信息,输出了一个列表,列表中每个元素为一行数据,是dict类型,每个key是列名,value是列对应的值。
1.4 指定index输出
df.to_dict('index')
Out[8]: {'row1': {'col1': 1, 'col2': 0.5}, 'row2': {'col1': 2, 'col2': 0.75}}
相比record来说,保留了index信息,输出为dict类型,key为index名称,value是对应行的内容。
1.5 指定mapping类型
df.to_dict(into=OrderedDict)
Out[10]:
OrderedDict([('col1', OrderedDict([('row1', 1), ('row2', 2)])),
('col2', OrderedDict([('row1', 0.5), ('row2', 0.75)]))])
dd = defaultdict(list)
df.to_dict('records', into=dd)
Out[12]:
[defaultdict(list, {'col1': 1, 'col2': 0.5}),
defaultdict(list, {'col1': 2, 'col2': 0.75})]
完结。。。
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html