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

相关文章

  • pytorch 如何打印网络回传梯度

    pytorch 如何打印网络回传梯度

    这篇文章主要介绍了pytorch 实现打印网络回传梯度的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-05-05
  • Python快速从注释生成文档的方法

    Python快速从注释生成文档的方法

    这篇文章主要介绍了Python快速从注释生成文档的方法的相关资料,非常的简单实用,需要的朋友可以参考下
    2016-12-12
  • 关于python pygame游戏进行声音添加的技巧

    关于python pygame游戏进行声音添加的技巧

    这篇文章主要给大家分享的是pygame游戏进行声音添加的方法,这文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
    2021-10-10
  • 关于python的mmh3库安装以及使用详解

    关于python的mmh3库安装以及使用详解

    这篇文章主要介绍了关于python的mmh3库安装以及使用详解,哈希方法主要有MD、SHA、Murmur、CityHash、MAC等几种方法,mmh3全程murmurhash3,是一种非加密的哈希算法,常用于hadoop等分布式存储情境中,需要的朋友可以参考下
    2023-07-07
  • Python使用pyaudio实现录音功能

    Python使用pyaudio实现录音功能

    pyaudio是一个跨平台的音频I/O库,使用PyAudio可以在Python程序中播放和录制音频,本文将利用它实现录音功能,并做到停止说话时自动结束
    2023-05-05
  • django基于cors解决跨域请求问题详解

    django基于cors解决跨域请求问题详解

    这篇文章主要介绍了django基于cors解决跨域请求问题详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-08-08
  • 解决python3 Pycharm上连接数据库时报错的问题

    解决python3 Pycharm上连接数据库时报错的问题

    今天小编就为大家分享一篇解决python3 Pycharm上连接数据库时报错的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-12-12
  • Python Django框架中表单的用法详解

    Python Django框架中表单的用法详解

    这篇文章主要为大家详细介绍了Python Django框架中表单的用法,例如表单的验证以及利用表单实现文件上传等,感兴趣的小伙伴可以了解一下
    2022-06-06
  • Django如何实现上传图片功能

    Django如何实现上传图片功能

    这篇文章主要介绍了Django如何实现上传图片功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-08-08
  • 一文秒懂pandas中iloc()函数

    一文秒懂pandas中iloc()函数

    iloc[]函数属于pandas库全称为index location,即对数据进行位置索引,从而在数据表中提取出相应的数据,本文通过实例代码介绍pandas中iloc()函数,感兴趣的朋友一起看看吧
    2023-04-04

最新评论