# -*- coding: utf-8 -*- # @File : base_use.py # @Date : 2018-07-25 # @Author : Peng Shiyu import numpy as np # 一维数组 animals = np.array(["pig", "dog", "cat"]) print(type(animals), animals) # <class 'numpy.ndarray'> ['pig' 'dog' 'cat'] print(animals[1]) # dog # 二维数组 X = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(type(X), X) # <class 'numpy.ndarray'> # [[1 2 3] # [4 5 6] # [7 8 9]] print(X[1][1]) # 5 X = np.array(range(6)).reshape(2, 3) print(X) """ [[0 1 2] [3 4 5]] """ # 三维数组 X = np.arange(24).reshape(2, 3, 4) print(X) """ [[[ 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(X.ndim) # 3 # 形状 print(X.shape) # (2, 3, 4) z, y, x # x, y, z 对应的shape元组是从右往左数的 # 打开图片(540 * 258) 长 * 宽 from matplotlib.pylab import plt image = plt.imread("images/baidu.png") print(image.shape) # (258, 540, 4) # (y, x, c) # axis 0, axis 1, axis 2 # 抽象座标轴顺序从左向右。指定哪个轴,就只在哪个轴向操作,其他轴不受影响。 # 排序 data = np.arange(12) np.random.shuffle(data) data = data.reshape(3, 4) print(data) """ [[ 2 5 7 8] [ 4 0 10 3] [ 1 11 6 9]] """ data = np.array([ [2, 5, 7, 8], [4, 0, 10, 3], [1, 11, 6, 9], ]) print(np.sort(data, axis=0)) """ [[ 1 0 6 3] [ 2 5 7 8] [ 4 11 10 9]] """ print(np.sort(data, axis=1)) """ [[ 2 5 7 8] [ 0 3 4 10] [ 1 6 9 11]] """ """ 理解轴: shape: (3, 4) axis: 0, 1 AXIS: y, x """ # 求和、均值、方差、最大、最小、累加、累乘 # sum,mean,std,var,min,max 会导致这个轴被压扁,缩减为一个数值 data = np.arange(24).reshape(2, 3, 4) print(data) """ [[[ 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(np.sum(data, axis=0)) print(np.sum(data, axis=1)) print(np.sum(data, axis=2)) """ [[12 14 16 18] [20 22 24 26] [28 30 32 34]] [[12 15 18 21] [48 51 54 57]] [[ 6 22 38] [54 70 86]] """ # 切片和索引 # 在索引中出现冒号(:),则本轴继续存在,如果只是一个数值,则本轴消失 data = np.arange(24).reshape(2, 3, 4) print(data) """ [[[ 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(data[0, :, :]) """ [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] """ print(data[0, 1, 2]) # 6 print(data[0:1, 1:2, 2:3]) # [[[6]]] 有三个 [,那么就是三维数组 # 拼接(concatenating) data = np.arange(4).reshape(2, 2) print(data) """ [[0 1] [2 3]] """ print(np.concatenate([data, data], axis=0)) print(np.concatenate([data, data], axis=1)) """ [[0 1] [2 3] [0 1] [2 3]] [[0 1 0 1] [2 3 2 3]] """ # reshape # ndarray 的数据在内存里以一维线性存放, # reshape 前后,数据没有变化,只是访问方式变了而已。