Numpy basic operations

Numpy basic operations

One, build an array

Note: numpy can build arrays with lists and tuples

1. List build array

import numpy as np
data1 = [5, 7, 9, 20]    #列表
arr1 = np.array(data1)
arr1

2. Tuples to build an array

data2 = (5, 7, 9, 20)     #元组
arr2 = np.array(data2)
arr2

3. Build a multidimensional array

data3 = [[1, 2, 3, 4],[5, 6, 7, 8]]   #多维数组
arr3 = np.array(data3)
arr3

4. Array ranks and element types

arr3.shape
#数组的形状(行和列)
arr3.dtype
#数组元素类型

5. All 1 array and all 0 array

np.zeros(8)
#生成8个元素全为1的数组
np.zeros((3,4))
#生成3行4列的全1数组
np.ones(4)
#生成全0数组
np.ones((4,6))
#生产4行6列的全0数组
np.empty((2, 2, 2))
#生成随机的2行2列的2维数据

6.arange generates an array

np.arange(10)
#生成从1到10(不包括10)的数组

7. Change the array to all 1s

arr5 = np.ones_like(arr3)
#将arr3的数据全部改为1
arr5

8. The astype() function changes the data type of a column in the DataFrame

注:
int32 --> float64
float64 --> int32
string_ --> float64

arr3 = arr1.astype('string_')
#改arr1的数据类型为字符串数组

2. Data reshaping and merging

1. Convert the array shape

Note: When the reshape parameter is -1, the number of new rows (columns) is automatically calculated based on the original array

arr = np.arange(9)
arr.reshape((3,3))
#将数组转换为3行3列的数组

2. Convert a multi-dimensional array to a 1-dimensional array

Note:
ravel(): If not necessary, a copy of the source data will not be generated.
flatten(): Return a copy of the source data.
squeeze(): Only the dimension of dimension 1 can be reduced

arr.ravel()
#转换为1维数组
arr.flatten()
#返回源数据的副本

3. Concatenate function to concatenate arrays

np.concatenate([arr1, arr2],axis=0)
#连接这2个数组,按行连接
np.concatenate([arr1, arr2],axis=1)
#按列连接

4. The vstack function stacks the array vertically (in line order)

np.vstack((arr1,arr2))
#按行顺序把这2个数组连接起来

5.hstack level (in column order) to stack the array

np.hstack((arr1, arr2))
#按列顺序把2个数组连接起来

6.split((ary, indices_or_sections, axis=0)

(1)ary: the array to be divided
(2) indicators_or_sections: if it is an integer, the number is divided equally, if it is an array, it is the position of the division along the axis (opening on the left and closed on the right)
(3)axis :The dimension along which to perform the tangential direction, the default is 0, and the horizontal division is performed. When it is 1, split longitudinally

np.split(arr,[2, 4])
#将数组以2个数组平均切分,并横向切分(即按列切分)

7. Array transpose, transformation (transpose, swapaxes)

arr.transpose((1,0))
#行和列互换位置
arr.T
#数组转置
arr.swapaxes(1, 2)
#将第2轴和第3轴数据交换

Three, random number

arr = np.random.randint(100, 200, size=(5, 4))
#返回100到200之间随机的整数,5行4列的数组
arr = np.random.randn(2, 3, 5)
#返回2行5列的3维数组,符合标准正态分布
arr = np.random.normal(4, 5, size=(3,5))
#返回3行5列,μ = 4,σ = 5的正态分布样本
np.random.permutation(arr)
#返回一个数组的随机排序(返回一个新的,不改变原数组)
np.random.shuffle(arr)
#打乱数组的排列顺序(改变原数组)

Fourth, index and slice

numpy slice explanation

Note:
This is a numpy slicing operation, the general structure is num[a:b,c:d], the comma is used as the separator during analysis,
and the subscript range of the num line to be taken before the comma (a to b-1) , After the comma is the subscript range of the num column to be taken (c to d-1); the
front is the row index, and the back is the column index.
If it is this num[:b,c:d], the value of a is not specified, then a is the minimum value of 0;
if it is this num[a:,c:d], the value of b is not specified, then b is Maximum value; the same applies to the case of c and d.

1. Index

arr[3]
#索引第4个数据
arr[-1]
#索引最后一个数据
arr[2] = 123
#改第3个数据为123
arr1 = arr[-3:-1]
#选取数组的后2个数据(除过最后一个数据)到新变量
arr1[:] = 77
#将新变量所有数据改为77(***此时原数组的值也改变***)
arr1 = arr[1].copy()
#生成新变量的副本(***此时再改变变量,不会改变原数组的值***)
arr[0][3]
#对多维数组可用二次索引(选取第一行数组的第4个数据)
arr[2,3]
#对多维数组多次索引,与上作用相同(选取第3行数据的第4个数据)

2. Index column

arr[:, 1]
#索取第2列
arr[:, 1:2]
#索取第1列(不包括第2列)
arr[2:, 1:]
#索取第3行后,第2列后的数组

3. Judgment Index

fruits == 'pear'
#判定fruits数组的每个数据是否为pear,是就为True,否就为False
datas[fruits == 'pear']
#按True的位置索引datas数组中的数组
datas[(fruits == 'apple') | (fruits == 'banana')]
#并集,选取这2个为True的数组数据
arr[[1, 3, 2]]
#索引第2行,第4行,第3行的数据
arr[[3, 2]][:, [2, 1]]
arr[np.ix_([3,2],[2, 1])]
#索引为[3,2],[3,1]
       [2,2],[2,1]

Explanation of where function

ix_ function explanation

Five, other operations

Explanation of cumsum function

Unique function explanation

in1d function explanation

Explanation of savetxt function

Explanation of loadtxt function

np.modf(arr)
#返回数组的整数和小数部分
arr.sum()
#返回数组所有数据之和
arr.mean()
#返回平均值
arr.std()
#返回总体标准偏差
arr.cumsum(0)
#返回按指定轴累加后的元素
arr.cumprod(1)
#累乘函数
arr.sort()
#升序排列
np.unique(fruits)
#去除fruits数组中重复的数据,并按从大到小的顺序排列输出
np.in1d(arr, [2,7])
#若数据为2和7,返回True,反之则False
np.savetxt('ch2ex1.csv', arr, fmt='%d',delimiter=',')
#将arr数组保存为csv文件
arr = np.loadtxt('ch2ex1.csv', delimiter=',')
#读取csv文件
np.dot(arr1,arr2)
#返回这2个数组的点积
from numpy.linalg import det
det(arr)
#计算数组的行列式

Six, image processing

from PIL import Image
import numpy as np
im = np.array(Image.open('C:/Users/LP/Desktop/2.76.jpeg'))
#加载图片
print(im.shape,im.dtype)
#输出图片尺寸和格式
b = [255, 255, 255] - im    #数组运算
new_im = Image.fromarray(b.astype('uint8'))  
new_im.save('C:/Users/LP/Desktop/2.79.jpeg')  
#保存为新图像

Guess you like

Origin blog.csdn.net/sgsdsdd/article/details/108897107