目录
目录
1.切片和索引
# -*- coding : utf-8 -*-
"""
@Time: 2021/7/29 21:51
@Author : zhanxuejie
@FileName: part01.py
@Software:PyCharm
"""
import numpy as np
a = [[1,2,3],
[4,5,6],
[7,8,9]]
# a = [1,2,3,4,5,6]
t = np.array(a)
# 选择行
print(t)
print(t[1:,:]) #第一行到最后一行
print(t[1]) #只取第一行
print(type(t[1:,:]))
print(type(t[1]))
#output:
# [[4 5 6]
# [7 8 9]]
# [4 5 6]
# <class 'numpy.ndarray'>
# <class 'numpy.ndarray'>
# 选择列
print(t[:,2:])
print(type(t[:,2:]))
print(t[:,2])
print(type(t[:,2]))
#output:
# [[3]
# [6]
# [9]]
# <class 'numpy.ndarray'>
# [3 6 9]
# <class 'numpy.ndarray'>
import numpy as np
t = np.array([[1,2,3,7],
[4,5,6,8],
[7,8,9,10],
[6,3,1,11]])
# 选择行列
print(t[1:,:3]) #选择连续的多行多列
# 不连续
print(t[[2,2],[3,2]]) #选择的是(2,3),(2,2)两个位置
# 索引
print(t[2,3])
#output: [[4 5 6]
# [7 8 9]
# [6 3 1]]
# [10 9]
# 10
2.赋值
# 赋值
t[1:,3]=3
print(t)
#output:[[1 2 3 7]
# [4 5 6 3]
# [7 8 9 3]
# [6 3 1 3]]
3.布尔索引
# 布尔索引
t[t>6] = 6 #大于6的赋值为6
print(t)
# output:
# [[1 2 3 6]
# [4 5 6 3]
# [6 6 6 3]
# [6 3 1 3]]
4.np.where()
# 三元运算符
print(np.where(t>6, 2, 3)) #大于6的赋值为2,其余赋值为3
# output:
# [[3 3 3 2]
# [3 3 3 2]
# [2 2 2 2]
# [3 3 3 2]]
5.裁剪
# 裁剪
a = t.clip(5,8) #大于5的替换为5,大于8 的替换为8
print(a)
# output:
# [[5 5 5 7]
# [5 5 6 8]
# [7 8 8 8]
# [6 5 5 8]]
6.转置
# 转置,三种方法效果一样
a = t.T
b = t.transpose()
c = t.swapaxes(1,0)
print(t)
print(a)
print(b)
print(c)
# output:
# [[ 1 2 3 7]
# [ 4 5 6 8]
# [ 7 8 9 10]
# [ 6 3 1 11]]
#
# [[ 1 4 7 6]
# [ 2 5 8 3]
# [ 3 6 9 1]
# [ 7 8 10 11]]
# [[ 1 4 7 6]
# [ 2 5 8 3]
# [ 3 6 9 1]
# [ 7 8 10 11]]
# [[ 1 4 7 6]
# [ 2 5 8 3]
# [ 3 6 9 1]
# [ 7 8 10 11]]
7.求极值
# 求极值,np.ptp()
print(t)
print(np.ptp(t)) #输出max-min
print(np.ptp(t,axis=0)) #输出y轴上max-min
print(np.ptp(t,axis=1)) #输出x轴上max-min
# output:
# [[ 1 2 3 7]
# [ 4 5 6 8]
# [ 7 8 9 10]
# [ 6 3 1 11]]
#
# 10
# [6 6 8 4]
# [ 6 4 3 10]