numpy教程:数组创建

blog.csdn.net/pipisorry/article/details/39406501

Array creation routines

There are 5 general mechanisms for creating arrays:

  1. Conversion from other Python structures (e.g., lists, tuples)
  2. Intrinsic numpy array array creation objects (e.g., arange, ones, zeros,etc.)
  3. Reading arrays from disk, either from standard or custom formats
  4. Creating arrays from raw bytes through the use of strings or buffers
  5. Use of special library functions (e.g., random)

可以通过dtype参数在创建时指定元素类型

声明一个没有初值的ndarray类型的变量

topic_list = ndarray([word_num, topic_num], dtype=object)

如果这样topic_list = ndarray([word_num, topic_num], dtype=str)就会报错:ValueError: data-type with unspecified variable length

[numpy recarray strings of variable length]

自定义数组元素类型

一个元素包含多个类型

b = np.array([(1, 2.0, 'Hello'), (2, 3.0, 'World')], dtype=[('A', '<i4'), ('B', '<f4'), ('C', 'S10')])
print(b)
numpy数组中添加元素类型为list

ul_array = np.zeros([num_users, len(locs)], dtype=list)

在NumPy中使用动态数组

NumPy的ndarray数组对象不能像list一样动态地改变其大小,在做数据采集时很不方便。本文介绍如何通过np.frombuffer()实现动态数组。

[在NumPy中使用动态数组]


皮皮blog



Ones and zeros

empty(shape[, dtype, order])Return a new array of given shape and type, without initializing entries.默认拷贝输入数据
empty_like(a[, dtype, order, subok])Return a new array with the same shape and type as a given array.当输入已经是一个ndarray时就不拷贝。
eye(N[, M, k, dtype])Return a 2-D array with ones on the diagonal and zeros elsewhere.
identity(n[, dtype])Return the identity array.
ones(shape[, dtype, order])Return a new array of given shape and type, filled with ones.
ones_like(a[, dtype, order, subok])Return an array of ones with the same shape and type as a given array.
zeros(shape[, dtype, order])Return a new array of given shape and type, filled with zeros.
zeros_like(a[, dtype, order, subok])Return an array of zeros with the same shape and type as a given array.
full(shape, fill_value[, dtype, order])Return a new array of given shape and type, filled with fill_value.
full_like(a, fill_value[, dtype, order, subok])Return a full array with the same shape and type as a given array.

通常,数组的元素开始都是未知的,但是它的大小已知。因此,NumPy提供了一些使用占位符创建数组的函数。这最小化了扩展数组的需要和高昂的运算代价。

生成bool数组

np.ones(..,dtype = bool)

bool数组取反

~bool_arr

生成无穷大数组矩阵

M_ic = np.full([3,4], fill_value=sys.maxsize, dtype=np.int64)

ones([...])

全一的矩阵, 如ones([3,4])会产生全1的3x4阶矩阵;     #这里的3,4要用[]或者()括起来,否则会出现错误:TypeError: data type not understood

zeros([....])

全0的矩阵;

不要使用这样的方式初始化字符串数组:

s = np.zeros([2,2], dtype='str')
print(s, s.dtype)
s[:, 0] = '123'
print(s, s.dtype)
[['' '']
 ['' '']] <U1
[['1' '']
 ['1' '']] <U1

这样初始化的字符串数组的字符串是1位的U1,而‘123’是U3,这样就不能赋值了。要使用

s = np.ndarray([2, 2], dtype=object)
这样就可以了。

empty( (2,3) )

        array([[  3.73603959e-262,   6.02658058e-154,   6.55490914e-260],
                   [  5.30498948e-313,   3.14673309e-307,   1.00000000e+000]])

Note:与zeros唯一不同的是 np.empty里面不是数据,而是给数据分配的空间地址

identity(n)

建立n*n的单位阵,这只能是一个方阵。

eye(N,M=None,k=0)

建立一个对角线是1其余值为0的矩阵,用k指定对角线的位置。M默认None

like函数

numpy中还提供了几个like函数,即按照某一个已知的数组的规模(几行几列)建立同样规模的特殊数组: zeros_like, ones_like, empty_like

Note:random.random([...]): 产生随机矩阵,如random.random([2,3])产生一个2x3维的随机数[Python和numpy生成随机数]

皮皮blog


From existing data

array(object[, dtype, copy, order, subok, ndmin])Create an array.
asarray(a[, dtype, order])Convert the input to an array.
asanyarray(a[, dtype, order])Convert the input to an ndarray, but pass ndarray subclasses through.
ascontiguousarray(a[, dtype])Return a contiguous array in memory (C order).
asmatrix(data[, dtype])Interpret the input as a matrix.
copy(a[, order])Return an array copy of the given object.
frombuffer(buffer[, dtype, count, offset])Interpret a buffer as a 1-dimensional array.
fromfile(file[, dtype, count, sep])Construct an array from data in a text or binary file.
fromfunction(function, shape, **kwargs)Construct an array by executing a function over each coordinate.
fromiter(iterable, dtype[, count])Create a new 1-dimensional array from an iterable object.
fromstring(string[, dtype, count, sep])A new 1-D array initialized from raw binary or text data in a string.
loadtxt(fname[, dtype, comments, delimiter, ...])Load data from a text file.

array和asarray函数:传递Python的序列对象创建数组

从列表创建

>>> from numpy import *
>>> a = array([[1,2.2,3],[4,5,6]])
>>> a.ndim
2
>>> a.size
6
>>> type(a)
<type numpy.ndarray>

从字符串创建

a = '****abc*.....'

l = array(list(a))

id_card_str = '42028118921027721'
id_card = np.array(list(id_card_str), dtype=int)
print(id_card)    #[4 2 0 2 8 1 1 8 9 2 1 0 2 7 7 2 1]

Note: 这种方法好像比下面的np.fromstring实用,fromstring指定转换类型时会将'4'转换成对应ASIC数值52。

多层嵌套的序列创建多维数组

First mode, buffer is None:
>>> np.ndarray(shape=(2,2), dtype=float, order=’F’)
array([[ -1.13698227e+002, 4.25087011e-303], [ 2.88528414e-306, 3.27025015e-309]]) #random
Second mode:
>>> np.ndarray((2,), buffer=np.array([1,2,3]), offset=np.int_().itemsize, dtype=int) 
# offset = 1*itemsize, i.e. skip first element
array([2, 3])

上面的例子都是先创建一个Python序列,然后通过array函数将其转换为数组,这样做显然效率不高。

如果传入一个实数

import numpy as np

x = 9.8
y = np.asarray(x)  # y = np.array(x)
print('type(y):', type(y))
print('y.ndim', y.ndim)
print('y', y)
print('y[0]', y[0])  # 出
type(y): <class 'numpy.ndarray'>
y.ndim 0
y 9.8

维度竟然是0维,类型却还是ndarray。

所以list转换2维数组时可以这样

ts_array = np.asarray(x).reshape([-1, 1]) if np.asarray(x).ndim <= 1 else np.asarray(x)

array和asarray的区别和联系

def asarray(a, dtype=None, order=None):
    return array(a, dtype, copy=False, order=order)
the main difference is that array (by default) will make a copy of the object, while asarray will not unless necessary.

b = array(a)当你传入一个ndarray参数a时,修改b的值不会改变a的值;而b = asarray(a)会改变a的值。

Note: 如果传入的参数a是一个python列表,则asarray也不会改变a的值,好像只是numpy内部类型如ndarray才可以的。

array和ndarray的区别和联系

np.array is just a convenience function to create an ndarray, it is not a class itself.

You can also create an array using np.ndarray, but it is not the recommended way. From the docstring of np.ndarray: Arrays should be constructed using array, zeros or empty ... The parameters given here refer to a low-level method (ndarray(...)) for instantiating an array.

Note: ndarray只是创建了一个ndarray对象,并没有传入数据的机制。传入的参数是ndarray对象的维度(初始化数据为随机的无穷小)。

[ What is the difference between ndarray and array in numpy?]

使用frombuffer, fromstring, fromfile等函数从字节序列创建数组

下面以fromstring为例:

>>> s = "abcdefgh"

Python的字符串实际上是字节序列,每个字符占一个字节,因此如果从字符串s创建一个8bit的整数数组的话,所得到的数组正好就是字符串中每个字符的ASCII编码:

>>> np.fromstring(s, dtype=np.int8)
array([ 97,  98,  99, 100, 101, 102, 103, 104], dtype=int8)

如果从字符串s创建16bit的整数数组,那么两个相邻的字节就表示一个整数,把字节98和字节97当作一个16位的整数,它的值就是98*256+97 = 25185。可以看出内存中是以little endian(低位字节在前)方式保存数据的。

>>> np.fromstring(s, dtype=np.int16)
array([25185, 25699, 26213, 26727], dtype=int16)
>>> 98*256+97
25185

如果把整个字符串转换为一个64位的双精度浮点数数组,那么它的值是:

>>> np.fromstring(s, dtype=np.float)
array([  8.54088322e+194])

显然这个例子没有什么意义,但是可以想象如果我们用C语言的二进制方式写了一组double类型的数值到某个文件中,那们可以从此文件读取相应的数据,并通过fromstring函数将其转换为float64类型的数组。

我们可以写一个Python的函数,它将数组下标转换为数组中对应的值,然后使用此函数创建数组:

>>> def func(i):
...   return i%4+1
...
>>> np.fromfunction(func, (10,))
array([ 1.,  2.,  3.,  4.,  1.,  2.,  3.,  4.,  1.,  2.])

fromfunction函数的第一个参数为计算每个数组元素的函数,第二个参数为数组的大小(shape),因为它支持多维数组,所以第二个参数必须是一个序列,本例中用(10,)创建一个10元素的一维数组。

下面的例子创建一个二维数组表示九九乘法表,输出的数组a中的每个元素a[i, j]都等于func2(i, j):

>>> def func2(i, j):
...     return (i+1) * (j+1)
...
>>> a = np.fromfunction(func2, (9,9))
>>> a
array([[  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.],
       [  2.,   4.,   6.,   8.,  10.,  12.,  14.,  16.,  18.],
       [  3.,   6.,   9.,  12.,  15.,  18.,  21.,  24.,  27.],
       [  4.,   8.,  12.,  16.,  20.,  24.,  28.,  32.,  36.],
       [  5.,  10.,  15.,  20.,  25.,  30.,  35.,  40.,  45.],
       [  6.,  12.,  18.,  24.,  30.,  36.,  42.,  48.,  54.],
       [  7.,  14.,  21.,  28.,  35.,  42.,  49.,  56.,  63.],
       [  8.,  16.,  24.,  32.,  40.,  48.,  56.,  64.,  72.],
       [  9.,  18.,  27.,  36.,  45.,  54.,  63.,  72.,  81.]])

皮皮blog


Creating record arrays(numpy.rec)

Creating character arrays (numpy.char)


Numerical ranges

arange([start,] stop[, step,][, dtype])Return evenly spaced values within a given interval.
linspace(start, stop[, num, endpoint, ...])Return evenly spaced numbers over a specified interval.
logspace(start, stop[, num, endpoint, base, ...])Return numbers spaced evenly on a log scale.
meshgrid(*xi, **kwargs)Return coordinate matrices from coordinate vectors.
mgridnd_grid instance which returns a dense multi-dimensional “meshgrid”.
ogridnd_grid instance which returns an open multi-dimensional “meshgrid”.

arange函数

类似于python的range函数,通过指定开始值、终值和步长来创建一维数组,注意数组不包括终值:

>>> np.arange(0,1,0.1)

array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])

Note:当arange使用浮点数参数时,由于有限的浮点数精度,通常无法预测获得的元素个数。因此,最好使用函数linspace去接收我们想要的元素个数来代替用range来指定步长。

linspace函数

通过指定开始值、终值和元素个数来创建一维数组,可以通过endpoint关键字指定是否包括终值,缺省设置是包括终值:

>>> np.linspace(0,1,12)

array([ 0. , 0.09090909, 0.18181818, 0.27272727, 0.36363636,

        0.45454545, 0.54545455, 0.63636364, 0.72727273, 0.81818182,

        0.90909091, 1. ])

linspace(start, end, num): 如linspace(0,1,11)结果为[0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1];linspace()是要包括终值的

logspace函数

和linspace类似,不过它创建等比数列,下面的例子产生1(10^0)到100(10^2)、有20个元素的等比数列:

>>> np.logspace(0, 2, 20)
array([   1.        ,    1.27427499,    1.62377674,    2.06913808,
          2.6366509 ,    3.35981829,    4.2813324 ,    5.45559478,
          6.95192796,    8.8586679 ,   11.28837892,   14.38449888,
         18.32980711,   23.35721469,   29.76351442,   37.92690191,
         48.32930239,   61.58482111,   78.47599704,  100.        ])

meshgrid

有时候需要在二维平面中生成一个网格,这时候可以使用 meshgrid 来完成这样的工作。

>>> nx, ny = (3, 2)
>>> x = np.linspace(0, 1, nx)
>>> y = np.linspace(0, 1, ny)
>>> xv, yv = meshgrid(x, y)
>>> xv
array([[ 0. ,  0.5,  1. ],
       [ 0. ,  0.5,  1. ]])
>>> yv
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  1.]])

meshgrid返回值x 对应网格的第一维,y 对应网格的第二维。
meshgrid返回的x, y 中有很多冗余的元素,这里提供了一个 sparse 的选项,在这个选项下,x, y 变成了单一的行向量和列向量。
meshgrid 可以设置轴排列的先后顺序:
默认为 indexing='xy' 即笛卡尔坐标,对于2维数组,返回行向量 x 和列向量 y
或者使用 indexing='ij' 即矩阵坐标,对于2维数组,返回列向量 x 和行向量 y。

Matlab中meshgrid 的用法
meshgrid(-1:.5:1, -1:.5:1)
Numpy的 meshgrid 并不支持这样的用法,但我们可以使用 ogrid / mgrid 来实现类似这样的用法。

ogrid:快速产生广播运算数组的ogrid对象

由于这种广播计算很常用,因此NumPy提供了快速产生能进行广播运算的数组的ogrid对象。

>>> x,y = np.ogrid[:5,:5]
>>> x
array([[0], [1], [2], [3], [4]])
>>> y
array([[0, 1, 2, 3, 4]])

ogrid是一个很有趣的对象,它和多维数组一样,用切片元组作为下标,返回的是一组可以用来广播计算的数组。其切片下标有两种形式:

  • 开始值:结束值:步长,和“np.arange(开始值, 结束值, 步长)”类似

  • 开始值:结束值:长度j,当第三个参数为虚数时,它表示所返回的数组的长度,和“np.linspace(开始值, 结束值, 长度)”类似:

    >>> x, y = np.ogrid[:1:4j, :1:3j]
    >>> x
    array([[ 0.        ],
           [ 0.33333333],
           [ 0.66666667],
           [ 1.        ]])
    >>> y
    array([[ 0. ,  0.5,  1. ]])

利用ogrid的返回值,我们能很容易计算二元函数在等间距网格上的值。

用ogird产生二维坐标网格,使用Mayavi的mlab模块快速绘制3D曲面[三维绘图之Mayavi.mlab]

使用ix_()构成网格上点的函数值

如果已经有了多个表示不同轴上的取值的一维数组。想计算出它们所构成的网格上的每点的函数值,可以使用ix_():

>>> x = np.array([0, 1, 4, 10])
>>> y = np.array([2, 3, 8])
>>> gy, gx = np.ix_(y, x)
>>> gx
array([[ 0,  1,  4, 10]])
>>> gy
array([[2], [3], [8]])
>>> gx+gy # 广播运算
array([[ 2,  3,  6, 12],
       [ 3,  4,  7, 13],
       [ 8,  9, 12, 18]])

在上面的例子中,通过ix_()将数组x和y转换成能进行广播运算的二维数组。注意数组y对应广播运算结果中的第0轴,而数组x与第1轴对应。

mgrid

mgrid对象的用法和ogrid对象类似,但是它所返回的是进行广播之后的数组。
np.ogrid[:5,:5]
Out[3]:
[array([[0],
        [1],
        [2],
        [3],
        [4]]), array([[0, 1, 2, 3, 4]])]

np.mgrid[:5,:5]
Out[2]:
array([[[0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2],
        [3, 3, 3, 3, 3],
        [4, 4, 4, 4, 4]],

       [[0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4]]])

不同grid函数之间的区别和联系

ogrid 相当于 meshgrid(indexing='ij', sparse=True)
mgrid 相当于 meshgrid(indexing='ij', sparse=False)
lz测试了一下,mgrid的确是用于多维情况,不能绘制一维的多维显示
如meshgrid可以利用linspace函数绘制x=0固定值时的一维高斯分布(这时meshgrid中的sparse不能为True)
x, y = np.meshgrid(np.linspace(0, 0, 400), np.linspace(-3, 3, 400))
ax.plot_surface(x, y, rv.pdf(np.dstack((x, y))), rstride=1, cstride=1)
但是mgrid要创建x,y后修改x为固定值
x, y = np.mgrid[-3:3:.15, -3:3:.15]
x = np.zeros_like(x)
ax.plot_surface(x, y, rv.pdf(np.dstack((x, y))), rstride=1, cstride=1)
[ 生成数组的函数]
[ NumPy mgrid vs. meshgrid]

皮皮blog


Building matrices

diag(v[, k])Extract a diagonal or construct a diagonal array.
diagflat(v[, k])Create a two-dimensional array with the flattened input as a diagonal.
tri(N[, M, k, dtype])An array with ones at and below the given diagonal and zeros elsewhere.
tril(m[, k])Lower triangle of an array.
triu(m[, k])Upper triangle of an array.
vander(x[, N, increasing])Generate a Vandermonde matrix.
皮皮blog


The Matrix class

mat(data[, dtype])Interpret the input as a matrix.
bmat(obj[, ldict, gdict])Build a matrix object from a string, nested sequence, or array.
[ numpy教程:矩阵matrix及其运算]

from:  http://blog.csdn.net/pipisorry/article/details/39406501
ref: Array creation routines*


转载于:https://my.oschina.net/u/3579120/blog/1508150

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值