python新建数值_1.3NumPy:创建和操作数值数据

本文档介绍了Python科学计算库NumPy的基础知识,包括Numpy数组的创建、操作、数据类型以及基本的可视化。讲解了如何利用NumPy进行高效的数值计算,如创建数组、索引、切片、基本数据类型以及使用随机数。还涉及到了数组的可视化,如使用matplotlib进行1D和2D绘图,并展示了如何处理缺失值和使用面具数组。此外,还提到了多项式运算、加载数据文件和处理图像等内容。
摘要由CSDN通过智能技术生成

Cloga:这份文档是euroscipy关于Python科学计算资源的一个教程。英文版地址为:http://scipy-lectures.github.io/,是学习Python科学计算生态体系很好的资料,因此,我会陆续将它翻译为中文,相关Gitbub地址为:https://github.com/cloga/scipy-lecture-notes_cn,完整的中文目录

作者:Emmanuelle Gouillart、Didrik Pinte、Ga?l Varoquaux 和 Pauli Virtanen

本章给出关于Numpy概述,Numpy是Python中高效数值计算的核心工具。

1.3.1 Numpy 数组对象

1.3.1.1 什么是Numpy以及Numpy数组?

1.3.1.1.1 Numpy数组

Python对象:

高级数值对象:整数、浮点

容器:列表(无成本插入和附加),字典(快速查找)

Numpy提供:

对于多维度数组的Python扩展包

更贴近硬件(高效)

为科学计算设计(方便)

也称为面向数组计算

import numpy as np

a = np.array([0, 1, 2, 3])

aarray([0, 1, 2, 3])

例如,数组包含:

实验或模拟在离散时间阶段的值

测量设备记录的信号,比如声波

图像的像素、灰度或颜色

用不同X-Y-Z位置测量的3-D数据,例如MRI扫描

...

为什么有用:提供了高速数值操作的节省内存的容器。

L = range(1000)

%timeit [i**2 for i in L]loops, best of 3: 93.7 μs per loopa = np.arange(1000)

%timeit a**2loops, best of 3: 2.16 μs per loop

1.3.1.1.2 Numpy参考文档

np.array?

String Form:

Docstring:

array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0, ...

查找东西:

np.lookfor('create array')Search results for 'create array'

---------------------------------

numpy.array

Create an array.

numpy.memmap

Create a memory-map to an array stored in a *binary* file on disk.

numpy.diagflat

Create a two-dimensional array with the flattened input as a diagonal.

numpy.fromiter

Create a new 1-dimensional array from an iterable object.

numpy.partition

Return a partitioned copy of an array.

numpy.ma.diagflat

Create a two-dimensional array with the flattened input as a diagonal.

numpy.ctypeslib.as_array

Create a numpy array from a ctypes array or a ctypes POINTER.

numpy.ma.make_mask

Create a boolean mask from an array.

numpy.ctypeslib.as_ctypes

Create and return a ctypes object from a numpy array. Actually

numpy.ma.mrecords.fromarrays

Creates a mrecarray from a (flat) list of masked arrays.

numpy.lib.format.open_memmap

Open a .npy file as a memory-mapped array.

numpy.ma.MaskedArray.__new__

Create a new masked array from scratch.

numpy.lib.arrayterator.Arrayterator

Buffered iterator for big arrays.

numpy.ma.mrecords.fromtextfile

Creates a mrecarray from data stored in the file `filename`.

numpy.asarray

Convert the input to an array.

numpy.ndarray

ndarray(shape, dtype=float, buffer=None, offset=0,

numpy.recarray

Construct an ndarray that allows field access using attributes.

numpy.chararray

chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0,

numpy.pad

Pads an array.

numpy.sum

Sum of array elements over a given axis.

numpy.asanyarray

Convert the input to an ndarray, but pass ndarray subclasses through.

numpy.copy

Return an array copy of the given object.

numpy.diag

Extract a diagonal or construct a diagonal array.

numpy.load

Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files.

numpy.sort

Return a sorted copy of an array.

numpy.array_equiv

Returns True if input arrays are shape consistent and all elements equal.

numpy.dtype

Create a data type object.

numpy.choose

Construct an array from an index array and a set of arrays to choose from.

numpy.nditer

Efficient multi-dimensional iterator object to iterate over arrays.

numpy.swapaxes

Interchange two axes of an array.

numpy.full_like

Return a full array with the same shape and type as a given array.

numpy.ones_like

Return an array of ones with the same shape and type as a given array.

numpy.empty_like

Return a new array with the same shape and type as a given array.

numpy.zeros_like

Return an array of zeros with the same shape and type as a given array.

numpy.asarray_chkfinite

Convert the input to an array, checking for NaNs or Infs.

numpy.diag_indices

Return the indices to access the main diagonal of an array.

numpy.ma.choose

Use an index array to construct a new array from a set of choices.

numpy.chararray.tolist

a.tolist()

numpy.matlib.rand

Return a matrix of random values with given shape.

numpy.savez_compressed

Save several arrays into a single file in compressed ``.npz`` format.

numpy.ma.empty_like

Return a new array with the same shape and type as a given array.

numpy.ma.make_mask_none

Return a boolean mask of the given shape, filled with False.

numpy.ma.mrecords.fromrecords

Creates a MaskedRecords from a list of records.

numpy.around

Evenly round to the given number of decimals.

numpy.source

Print or write to a file the source code for a Numpy object.

numpy.diagonal

Return specified diagonals.

numpy.histogram2d

Compute the bi-dimensional histogram of two data samples.

numpy.fft.ifft

Compute the one-dimensional inverse discrete Fourier Transform.

numpy.fft.ifftn

Compute the N-dimensional inverse discrete Fourier Transform.

numpy.busdaycalendar

A business day calendar object that efficiently stores informationnp.con*?

np.concatenate

np.conj

np.conjugate

np.convolve

1.3.1.1.3 导入惯例

导入numpy的推荐惯例是:

import numpy as np

1.3.1.2 创建数组

1.3.1.2.1 手动构建数组

1-D:

a = np.array([0, 1, 2, 3])

aarray([0, 1, 2, 3])a.ndima.shape(4,)len(a)

2-D,3-D,...:

b = np.array([[0, 1, 2], [3, 4, 5]]) # 2 x 3 数组

barray([[0, 1, 2],

[3, 4, 5]])b.ndimb.shape(2, 3)len(b) # 返回一个纬度的大小c = np.array([[[1], [2]], [[3], [4]]])

carray([[[1],

[2]],

[[3],

[4]]])c.shape(2, 2, 1)

练习:简单数组

创建一个简单的二维数组。首先,重复上面的例子。然后接着你自己的:在第一行从后向前数奇数,接着第二行数偶数?

在这些数组上使用函数len()、numpy

.shape()。他们有什么关系?与数组的ndim属性间呢?

1.3.1.2.2 创建数组的函数

实际上,我们很少一个项目接一个项目输入...

均匀分布:

a = np.arange(10) # 0 .. n-1 (!)

aarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])b = np.arange(1, 9, 2) # 开始,结束(不包含),步长

barray([1, 3, 5, 7])

或者通过一些数据点:

c = np.linspace(0, 1, 6) # 起点、终点、数据点

carray([ 0. , 0.2, 0.4, 0.6, 0.8, 1. ])d = np.linspace(0, 1, 5, endpoint=False)

darray([ 0. , 0.2, 0.4, 0.6, 0.8])

普通数组:

a = np.ones((3, 3)) # 提示: (3, 3) 是元组

aarray([[ 1., 1., 1.],

[ 1., 1., 1.],

[ 1., 1., 1.]])b = np.zeros((2, 2))

barray([[ 0., 0.],

[ 0., 0.]])c = np.eye(3)

carray([[ 1., 0., 0.],

[ 0., 1., 0.],

[ 0., 0., 1.]])d = np.diag(np.array([1, 2, 3, 4]))

darray([[1, 0, 0, 0],

[0, 2, 0, 0],

[0, 0, 3, 0],

[0, 0, 0, 4]])

np.random: 随机数 (Mersenne Twister PRNG) :

a = np.random.rand(4) # [0, 1] 的均匀分布

aarray([ 0.05504731, 0.38154156, 0.39639478, 0.22379146])b = np.random.randn(4) # 高斯

barray([ 0.9895903 , 1.85061188, 1.0021666 , -0.63782069])np.random.seed(1234) # 设置随机种子np.random.rand?

练习:用函数创建数组

* 实验用arange、linspace、ones、zeros、eye和diag。

* 用随机数创建不同类型的数组。

* 在创建带有随机数的数组前设定种子。

* 看一下函数np.empty。它能做什么?什么时候会比较有用?

1.3.1.3基础数据类型

你可能已经发现,在一些情况下,数组元素显示带有点(即 2. VS 2)。这是因为所使用的数据类型不同:

a = np.array([1, 2, 3])

a.dtypedtype('int64')b = np.array([1., 2., 3.])

barray([ 1., 2., 3.])

不同的数据类型可以更紧凑的在内存中存储数据,但是大多数时候我们都只是操作浮点数据。注意,在上面的例子中,Numpy自动从输入中识别了数据类型。

你可以明确的指定想要的类型:

c = np.array([1, 2, 3], dtype=float)

c.dtypedtype('float64')

默认数据类型是浮点:

a = np.ones((3, 3))

a.dtypedtype('float64')

其他类型:

复数:

d = np.array([1+2j, 3+4j, 5+6*1j])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值