{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Numpy能从磁盘直接存储和加载数据,不论是文本格式还是二进制模式。这里我们只考虑Numpy的二进制模式,因为大多数用户更喜欢用pandas或其他工具来加载text或tabular数据。\n", "\n", "np.save和np.load。数组会以未压缩的原始二进制模式被保存,后缀为.npy:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "\n", "arr = np.arange(10)\n", "np.save('../examples/some_array', arr)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "即使保存的时候没有加后缀,也会被自动加上。可以用np.load来加载数组:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "np.load('../examples/some_array.npy')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "用np.savez能保存多个数组,还可以指定数组对应的关键字,不过是未压缩的npz格式:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": true }, "outputs": [], "source": [ "np.savez('../examples/array_archive.npz', a=arr, b=arr)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "加载.npz文件的时候,得到一个dict object:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "arch = np.load('../examples/array_archive.npz')\n", "arch['b']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "可以用np.savez_compressed来压缩文件:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": true }, "outputs": [], "source": [ "np.savez_compressed('../examples/array_compressed.npz', a=arr, b=arr)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python [py35]", "language": "python", "name": "Python [py35]" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.2" } }, "nbformat": 4, "nbformat_minor": 0 }