1. dict转化为DataFrame
根据dict形式的不同,选择不同的转化方式,主要用的方法是 DataFrame.from_dict,其官方文档如下:
-
pandas.DataFrame.from_dict
- classmethod DataFrame.from_dict(data, orient=‘columns’, dtype=None, columns=None)
- Construct DataFrame from dict of array-like or dicts.
- Creates DataFrame object from dictionary by columns or by index allowing dtype specification.
-
Parameters
- data [dict] Of the form {field : array-like} or {field : dict}.
-
orient [{‘columns’, ‘index’}, default ‘columns’] The “orientation” of the data. If the
keys of the passed dict should be the columns of the resulting DataFrame, pass ‘columns’ (default). Otherwise if the keys should be rows, pass ‘index’. - dtype [dtype, default None] Data type to force, otherwise infer.
-
columns [list, default None] Column labels to use when orient=‘index’. Raises
a ValueError if used with orient=‘columns’.
-
Returns
- DataFrame
1.1 dict的value是不可迭代的对象
1. from_dict
如果用from_dict,必须设置orient=‘index’,要不然会报错,也就是dict的key不能用于columns。
dic = {'name': 'abc', 'age': 18, 'job': 'teacher'} df = pd.DataFrame.from_dict(dic, orient='index') print(df)
Out:
0
name abc
age 18
job teacher
2. 土法转换
dict先转换成Series,再将Series转换成Dataframe,再重设索引,重命名列名。
dic = {'name': 'abc', 'age': 18, 'job': 'teacher'} df = pd.DataFrame(pd.Series(dic), columns=['value']) df = df.reset_index().rename(columns={'index': 'key'}) print(df)
Out:
key value
0 name abc
1 age 18
2 job teacher
1.2 dict的value为list
1.2.1 当没有指定orient时,默认将key值作为列名。(列排列)
dic = {'color': ['blue', 'green', 'orange', 'yellow'], 'size': [15, 20, 20, 25]} df = pd.DataFrame.from_dict(dic) print(df)
Out:
color size
0 blue 15
1 green 20
2 orange 20
3 yellow 25
1.2.2 当指定orient=‘index’时,将key值作为行名。(行排列)
dic = {'color': ['blue', 'green', 'orange', 'yellow'], 'size': [15, 20, 20, 25]} df = pd.DataFrame.from_dict(dic, orient='index', columns=list('ABCD')) print(df)
Out:
A B C D
color blue green orange yellow
size 15 20 20 25
总结:
orient指定为什么, dict的key就作为什么。
如orient=‘index’,那么dict的key就作为行索引。
1.3 dict的value是dict
1.3.1 使用默认的orient属性,key将当做columns使用
dic = {'Jack': {'hobby': 'football', 'age': 19}, 'Tom': {'hobby': 'basketball', 'age': 24}, 'Lucy': {'hobby': 'swimming', 'age': 20}, 'Lily': {'age': 21}} df = pd.DataFrame.from_dict(dic) print(df)
Out:
Jack Tom Lucy Lily
age 19 24 20 21.0
hobby football basketball swimming NaN
这是使用了dict嵌套dict的写法,外层dict的key为columns,values内的dict的keys为rows的名称,缺省的值为NAN
1.3.2 当指定orient=‘index’时,内部的key为columns,外部的key为index
当修改orient的默认值’columns’为’index’,内部的key为DataFrame的columns,外部的key为DataFrame的index
dic = {'Jack': {'hobby': 'football', 'age': 19}, 'Tom': {'hobby': 'basketball', 'age': 24}, 'Lucy': {'hobby': 'swimming', 'age': 20}, 'Lily': {'age': 21}} df = pd.DataFrame.from_dict(dic, orient='index') print(df)
Out:
hobby age
Jack football 19
Lily NaN 21
Lucy swimming 20
Tom basketball 24
注意:
当时使用dict嵌套dict的时候,设置了orient=’index’后,不能再为columns命名了,此时,如果设定columns,只会筛选出在原DataFrame中已经存在的columns。
dic = {'Jack': {'hobby': 'football', 'age': 19}, 'Tom': {'hobby': 'basketball', 'age': 24}, 'Lucy': {'hobby': 'swimming', 'age': 20}, 'Lily': {'age': 21}} df = pd.DataFrame.from_dict(dic, orient='index', columns=['age', 'A']) print(df)
Out:
age A
Jack 19 NaN
Lily 21 NaN
Lucy 20 NaN
Tom 24 NaN
2.DataFrame转换成 dict
DataFrame.to_dict官方文档:
-
pandas.DataFrame.to_dict
- DataFrame.to_dict(orient=‘dict’, into=)
- Convert the DataFrame to a dictionary.
- The type of the key-value pairs can be customized with the parameters (see below).
-
Parameters
-
orient [str {‘dict’, ‘list’, ‘series’, ‘split’, ‘records’, ‘index’}] Determines the type of the
values of the dictionary.
• ‘dict’ (default) : dict like {column -> {index -> value}}
• ‘list’ : dict like {column -> [values]}
• ‘series’ : dict like {column -> Series(values)}
• ‘split’ : dict like {‘index’ -> [index], ‘columns’ -> [columns], ‘data’ -> [values]}
• ‘records’ : list like [{column -> value}, . . . , {column -> value}]
• ‘index’ : dict like {index -> {column -> value}}
Abbreviations are allowed. s indicates series and sp indicates split. -
into [class, default dict] The collections.abc.Mapping subclass used for all Mappings
in the return value. Can be the actual class or an empty instance of the mapping
type you want. If you want a collections.defaultdict, you must pass it initialized.
-
orient [str {‘dict’, ‘list’, ‘series’, ‘split’, ‘records’, ‘index’}] Determines the type of the
- Returnsdict, list or collections.abc.Mapping Return a collections.abc.Mapping object representing the DataFrame. The resulting transformation depends on the orient parameter.
-
函数种只需要填写一个参数:orient 即可,但对于写入orient的不同,字典的构造方式也不同,官网一共给出了6种,并且其中一种是列表类型:
- orient =‘dict’,是函数默认的,转化后的字典形式:{column(列名) : {index(行名) : value(值) )}};
- orient =‘list’ ,转化后的字典形式:{column(列名) :{ values }};
- orient=‘series’ ,转化后的字典形式:{column(列名) : Series (values) (值)};
- orient =‘split’ ,转化后的字典形式:{‘index’ : [index],‘columns’ :[columns],’data‘ : [values]};
- orient =‘records’ ,转化后是 list形式:[{column(列名) : value(值)}…{column:value}];
- orient =‘index’ ,转化后的字典形式:{index(值) : {column(列名) : value(值)}};
-
说明:上面中 value 代表数据表中的值,column表示列名,index 表示行名
df = pd.DataFrame({'col_1': [5, 6, 7], 'col_2': [0.35, 0.96, 0.55]}, index=['row1', 'row2', 'row3']) print(df)
Out:
col_1 col_2
row1 5 0.35
row2 6 0.96
row3 7 0.55
2.1 orient =‘list’
{column(列名) : { values }};
生成dict中 key为各列名,value为各列对应值的list
df = df.to_dict(orient='list') print(df)
Out:
{‘col_1’: [5, 6, 7], ‘col_2’: [0.35, 0.96, 0.55]}
2.2 orient =‘dict’
{column(列名) : {index(行名) : value(值) )}}
df = df.to_dict(orient='dict') print(df)
Out:
{‘col_1’: {‘row1’: 5, ‘row2’: 6, ‘row3’: 7}, ‘col_2’: {‘row1’: 0.35, ‘row2’: 0.96, ‘row3’: 0.55}}
2.3 orient =‘series’
{column(列名) : Series (values) (值)};
orient =‘series’ 与 orient = ‘list’ 唯一区别就是,这里的 value 是 Series数据类型,而前者为列表类型.
df = df.to_dict(orient='series') print(df)
Out:
{‘col_1’: row1 5
row2 6
row3 7
Name: col_1, dtype: int64, ‘col_2’: row1 0.35
row2 0.96
row3 0.55
Name: col_2, dtype: float64}
2.4 orient =‘split’
{‘index’ : [index],‘columns’ :[columns],’data‘ : [values]};orient =‘split’ 得到三个键值对,列名、行名、值各一个,value统一都是列表形式;
df = df.to_dict(orient='split') print(df)
Out:
{‘index’: [‘row1’, ‘row2’, ‘row3’], ‘columns’: [‘col_1’, ‘col_2’], ‘data’: [[5, 0.35], [6, 0.96], [7, 0.55]]}
2.5 orient =‘records’
[{column:value(值)},{column:value}…{column:value}];注意的是,orient =‘records’ 返回的数据类型不是 dict ; 而是list 列表形式,由全部列名与每一行的值形成一一对应的映射关系:
df = df.to_dict(orient='records') print(df)
Out:
[{‘col_1’: 5, ‘col_2’: 0.35}, {‘col_1’: 6, ‘col_2’: 0.96}, {‘col_1’: 7, ‘col_2’: 0.55}]
这个构造方式的好处就是,很容易得到 列名与某一行值形成得字典数据;例如我想要第1行{column:value}得数据:
print(df.to_dict('records')[1])
Out:
{‘col_1’: 6, ‘col_2’: 0.96}
2.6 orient =‘index’
{index:{culumn:value}};
orient =’index’与orient =‘dict’ 用法刚好相反,求某一行中列名与值之间一一对应关系(查询效果与orient =‘records’ 相似):
print(df.to_dict('index'))
Out:
{‘row1’: {‘col_1’: 5, ‘col_2’: 0.35}, ‘row2’: {‘col_1’: 6, ‘col_2’: 0.96}, ‘row3’: {‘col_1’: 7, ‘col_2’: 0.55}}
查询行名为 row1 列名与值一一对应字典数据类型
print(df.to_dict('index')['row1'])
Out:
{‘col_1’: 5, ‘col_2’: 0.35}
到此这篇关于pandas中DataFrame字典互转的实现的文章就介绍到这了,更多相关pandas DataFrame字典互转内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!