3.NumPy - 数组属性

时间:2023-03-09 15:01:37
3.NumPy - 数组属性

1、ndarray.shape

  这一数组属性返回一个包含数组维度的元组,它也可以用于调整数组大小

# -*- coding: utf-8 -*-

import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print a
print "Ndarray数组的维度为:"
print a.shape print "调整数组大小--a.shape = (3,2)"
a.shape = (3,2)
print a print "调整数组大小--a.reshape = (2,3)"
a.reshape(2,3)
print a

运行结果:

[[1 2 3]
[4 5 6]]
Ndarray数组的维度为:
(2L, 3L)
调整数组大小--a.shape = (3,2)
[[1 2]
[3 4]
[5 6]]
调整数组大小--a.reshape = (2,3)
[[1 2]
[3 4]
[5 6]]

2、ndarray.ndim:返回数组的维数

# -*- coding: utf-8 -*-

import numpy as np
#等间隔数字的数组
a = np.arange(24)
print a #[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
print a.ndim #返回数组的维数:1
#现在调整其维数
b = a.reshape(2,4,3) #现在拥有三个维度:三维数组包含两个二维数组,每一个二维数组里面包含4x3的一维数组
print b

运行结果:

[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
1
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]] [[12 13 14]
[15 16 17]
[18 19 20]
[21 22 23]]]

3、ndarray.itemsize:返回数组中每个元素的字节单位长度

# -*- coding: utf-8 -*-

import numpy as np
#数组的 dtype 为 int8(一个字节)
x = np.array([1,2,3,4,5], dtype = np.int8)
print x #[1 2 3 4 5]
print x.itemsize #:
print '-----------------------'
#数组的 dtype 现在为 float32(四个字节)
x = np.array([1,2,3,4,5], dtype = np.float32)
print x.itemsize #

4:NumPy - 数组创建

4.1:numpy.empty

numpy.empty(shape, dtype = float, order = 'C')   #它创建指定形状和dtype的未初始化数组

构造器接受下列参数:

序号 参数及描述
1. Shape 空数组的形状,整数或整数元组
2. Dtype 所需的输出数组类型,可选
3. Order 'C'为按行的 C 风格数组,'F'为按列的 Fortran 风格数组
import numpy as np
x = np.empty([3,2], dtype = int)
print x

运行结果:注意:数组元素为随机值,因为它们未初始化

[[1577124050          0]
  [1577157920 0]
  [1668244575 2645855]]

4.2:numpy.zeros:返回特定大小,以 0 填充的新数组。

numpy.zeros(shape, dtype = float, order = 'C')

构造器接受下列参数:

序号 参数及描述
1. Shape 空数组的形状,整数或整数元组
2. Dtype 所需的输出数组类型,可选
3. Order 'C'为按行的 C 风格数组,'F'为按列的 Fortran 风格数组
# -*- coding: utf-8 -*-

import numpy as np
#含有 5 个 0 的数组,默认类型为 float
x = np.zeros(5)
print x x = np.zeros((5,), dtype = np.int)
print x #自定义类型
x = np.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')])
print x
[0. 0. 0. 0. 0.]
[0 0 0 0 0]
[[(0, 0) (0, 0)]
[(0, 0) (0, 0)]]

4.3:numpy.ones返回特定大小,以 1 填充的新数组

numpy.ones(shape, dtype = None, order = 'C')

构造器接受下列参数:

序号 参数及描述
1. Shape 空数组的形状,整数或整数元组
2. Dtype 所需的输出数组类型,可选
3. Order 'C'为按行的 C 风格数组,'F'为按列的 Fortran 风格数组

例 1

# 含有 5 个 1 的数组,默认类型为 float
import numpy as np
x = np.ones(5) print x

输出如下:

[ 1.  1.  1.  1.  1.]

例 2

import numpy as np
x = np.ones([2,2], dtype = int)
print x

输出如下:

[[1  1]
[1 1]]