Numpy之多维数组

查看数组的维度

ndim

查看数组的维度。

import numpy as np
a1 = np.array([1,2,3])
#打印维度
print(a1.ndim)
out: 1
#二维数组
a2 = np.array([[1,2,3],[4,5,6]])
print(a2.ndim)
out: 2
#三维数组
a3 = np.array([
 [
 [1,2,3],  [4,5, 6]],
 [[7,8, 9],
 [10, 11, 12]]])
print(a3.ndim)
out: 3

shape

表示各位维度大小的元组。返回的是一个元组。

#当前数组的构成 几行几列
print(a1.shape)
print(a2.shape)
print(a3.shape)
out: (3,)
      (2, 3)
      (2, 2, 3)

reshape

数组变形

#变形 reshape
a4 = a3.reshape((2,6))# 变形成两行六列 注意与原来的数组乘积相同
print(a4)
print(a4.shape)

out: [[ 1  2  3  4  5  6]
 [ 7  8  9 10 11 12]]
(2, 6)
#变成一维数组
# a5 = a3.reshape((12,))
#第二种方式扁平化转化一维数组 不会修改原来的值
a5 = a3.flatten()# 快捷方式无论多少维直接变为一维数组
print(a5)
print(a5.ndim)
out: [ 1  2  3  4  5  6  7  8  9 10 11 12]
1

size

获取元素个数

#size获取元素个数
count = a3.size
print(count)
out: 12

itemsize

数组中每个元素占字节的大小,单位是字节

itemsize = a3.itemsize
print(itemsize)
print(a3.dtype)
out:out8
int64

  转载请注明: 空灵的Blog Numpy之多维数组

 上一篇
使用Python的30个技巧 使用Python的30个技巧
Tips#1. 变量交换 Example x, y = 10, 20 print(x, y) x, y = y, x print(x, y) Output 10 20 20 10 Tips#2. 链接比较运算符有时候比较运算符的聚
2018-03-11
下一篇 
Numpy之数组的切片和索引 Numpy之数组的切片和索引
一维数组的索引和切片 如果数组是一维的,那么索引和切片就是跟 python 的列表是一样的。 import numpy as np #1. 一维数组的索引和切片 a1 = np.arange(10) print(a1) #1.1 索引操
2018-02-23
  目录