python数据处理(数据集的格式转换)

摘要

本文总结常常用到的一些数据处理方法,主要是numpy和python 数组、列表、字典的操作。

一、保存N维数组(ndarray)到本地文件

本节参考原文在此,本节复述目的是防止丢失,时常复习。

1、需求

实际程序中,往往需要将运算结果(ndarray类型)保存到本地,以便进行后续的数据分析。利用numpy.savetxt可以保存1维或2维数据到txt文件中,但无法保存3维以上的数据。比如对一个图像库提取的图像特征。
此时可以用numpy.savez方法来保存3维以上的数据。

2、接口

保存数据用numpy.savez

  • 可以保存任意多个N维数组,有两种保存方式:
  1. 用*args方式,比如np.savez('data',d1,d2,d3),它将会以以arr_0,arr_1,arr_2来表示d1,d2,d3的名字,用于访问数据时用。
  2. 用**kwds方式,比如np.savez('data',d1=d1,d2=d2,d3=d3),即指定了数组名,用于访问数据时用。
  • 保存后的本地文件为npz格式。
    需要载入数据时用np.load(file)方法
  • 载入后的对象为NpzFile对象,类似一个字典。可以通过NpzFile.files来查看该文件中,有哪些数据。进而再通过类似字典索引的方式来访问数据,详情见实例。
Signature: np.savez(file, *args, **kwds)
Docstring:
Save several arrays into a single file in uncompressed ``.npz`` format.

If arguments are passed in with no keywords, the corresponding variable
names, in the ``.npz`` file, are 'arr_0', 'arr_1', etc. If keyword
arguments are given, the corresponding variable names, in the ``.npz``
file will match the keyword names.

Parameters
----------
file : str or file
    Either the file name (string) or an open file (file-like object)
    where the data will be saved. If file is a string or a Path, the
    ``.npz`` extension will be appended to the file name if it is not
    already there.
args : Arguments, optional
    Arrays to save to the file. Since it is not possible for Python to
    know the names of the arrays outside `savez`, the arrays will be saved
    with names "arr_0", "arr_1", and so on. These arguments can be any
    expression.
kwds : Keyword arguments, optional
    Arrays to save to the file. Arrays will be saved in the file with the
    keyword names.

实例1:用*args方式保存数据

In [48]: d1 = np.random.randint(0,100,(2,2,2))

In [49]: d1
Out[49]: 
array([[[12, 72],
        [60, 41]],

       [[ 2,  6],
        [62, 53]]])

In [50]: d2, d3 = d1*10, d1*100

In [51]: np.savez('data',d1,d2,d3)

In [52]: data = np.load('data.npz')

In [53]: data.files
Out[53]: ['arr_0', 'arr_1', 'arr_2']

In [54]: data['arr_0']
Out[54]: 
array([[[12, 72],
        [60
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值