pandas中DataFrame字典互转的实现

 更新时间:2024年04月03日 11:44:04   作者:craftsman2020  
在数据处理和分析中,Pandas是一个非常强大的Python库,本文主要介绍了pandas中DataFrame字典互转的实现,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧

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=<class ‘dict’>)
    • 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.
    • 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字典互转内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 浅谈Python数学建模之线性规划

    浅谈Python数学建模之线性规划

    线性规划是运筹学中研究较早、发展较快、应用广泛、方法较成熟的一个重要分支,它是辅助人们进行科学管理的一种数学方法。研究线性约束条件下线性目标函数的极值问题的数学理论和方法
    2021-06-06
  • Python venv虚拟环境配置过程解析

    Python venv虚拟环境配置过程解析

    这篇文章主要介绍了Python venv虚拟环境配置过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-07-07
  • 用TensorFlow实现戴明回归算法的示例

    用TensorFlow实现戴明回归算法的示例

    这篇文章主要介绍了用TensorFlow实现戴明回归算法的示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-05-05
  • 详解python opencv图像混合算术运算

    详解python opencv图像混合算术运算

    这篇文章主要介绍了python opencv图像混合算术运算的相关知识,本文通过实例图文相结合给大家介绍的非常详细,需要的朋友可以参考下
    2021-09-09
  • Python中的元组(Tuple)操作实例详解

    Python中的元组(Tuple)操作实例详解

    Python 元组和列表很像,也是一个包含多个元素的集合,下面这篇文章主要给大家介绍了关于Python中元组(Tuple)操作的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-02-02
  • Python ttkbootstrap 制作账户注册信息界面的案例代码

    Python ttkbootstrap 制作账户注册信息界面的案例代码

    ttkbootstrap 是一个基于 tkinter 的界面美化库,使用这个工具可以开发出类似前端 bootstrap 风格的 tkinter 桌面程序。本文重点给大家介绍Python ttkbootstrap 制作账户注册信息界面的案例代码,感兴趣的朋友一起看看吧
    2022-02-02
  • Python使用国内镜像加速pip安装的方法讲解

    Python使用国内镜像加速pip安装的方法讲解

    在Python开发中,pip是一个非常重要的工具,用于安装和管理Python的第三方库,然而,在国内使用pip安装依赖时,往往会因为网络问题而导致速度缓慢甚至超时,为了解决这个问题,本文将详细介绍如何使用-i参数配置国内镜像源,加速pip的安装过程,需要的朋友可以参考下
    2025-02-02
  • Python 多进程、多线程效率对比

    Python 多进程、多线程效率对比

    这篇文章主要介绍了Python 多进程、多线程的效率对比,帮助大家选择适合的技术,感兴趣的朋友可以了解下
    2020-11-11
  • np.concatenate()函数的具体使用

    np.concatenate()函数的具体使用

    本文主要介绍了np.concatenate()函数的具体使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-03-03
  • 教你用Python实现Excel表格处理

    教你用Python实现Excel表格处理

    今天教各位小伙伴怎么用Python处理excel,文中有非常详细的代码示例及相关知识总结,对正在学习python的小伙伴们很有帮助,需要的朋友可以参考下
    2021-05-05

最新评论