1. 拷贝
1. 指向同一块内存
测试代码
a = np.arange(12)
print(a)
b = a
print(b is a)
# 修改矩阵b的结构
b.shape = 3, 4
# 矩阵a的结构也被修改
print(a.shape)
# 内存地址相同
print(id(a))
print(id(b))
结果
True
(3, 4)
2550115223472
2550115223472
2. 浅拷贝
虽然指向不同,但共用了数据值
测试代码
import numpy as np
a = np.arange(12)
c = a.view()
print(c is a)
c.shape = 2, 6
# a的结构没有修改
print(a.shape)
c[0, 4] = 1234
# id不相同
print(id(a))
print(id(c))
# 矩阵a数据值被修改了
print(a)
结果
False
(12,)
2433804093360
2433804093600
[ 0 1 2 3 1234 5 6 7 8 9 10 11]
3. 深拷贝
完全拷贝,互不影响
测试代码
import numpy as np
a = np.arange(12)
d = a.copy()
print(d is a)
d[0] = 9999
print(d)
print(a)
结果
False
[9999 1 2 3 4 5 6 7 8 9 10 11]
[ 0 1 2 3 4 5 6 7 8 9 10 11]
2. 排序
测试代码
import numpy as np
a = (10 * np.random.random(9)).reshape(3, 3)
print(a, '\n')
# 按行排序
print(np.sort(a, axis=1), '\n')
# 按列排序
print(np.sort(a, axis=0))
结果
[[1.21241773 5.58488323 7.64504609]
[6.15513022 2.22587255 2.1503628 ]
[4.93324292 8.81117338 0.67988218]]
[[1.21241773 5.58488323 7.64504609]
[2.1503628 2.22587255 6.15513022]
[0.67988218 4.93324292 8.81117338]]
[[1.21241773 2.22587255 0.67988218]
[4.93324292 5.58488323 2.1503628 ]
[6.15513022 8.81117338 7.64504609]]
3. 索引
1. 查找矩阵中最大值的索引
测试代码
import numpy as np
a = (10 * np.random.random(9)).reshape(3, 3)
print(a, '\n')
# 查找最大索引
# 按行查找
print(np.argmax(a, axis=1))
# 按列查找
print(np.argmax(a, axis=0))
结果
[[0.76985512 1.15680858 1.92320952]
[2.34328735 3.8422487 7.74842892]
[9.70479806 5.39034717 3.94886746]]
[2 2 0]
[2 2 1]
2. 根据索引查找最大的值
测试代码
import numpy as np
a = (10 * np.random.random(9)).reshape(3, 3)
print(a, '\n')
ind = a.argmax(axis=0)
# a.shape[1]=4,表示共有4列
dataMax = a[ind, range(a.shape[1])]
print(dataMax)
结果
[[8.17963622 2.39383316 9.89705797]
[1.29138537 2.31341151 7.90212905]
[9.39447502 3.55331397 9.41707734]]
[9.39447502 3.55331397 9.89705797]
3. 索引排序
测试代码
import numpy as np
a = (10 * np.random.random(9)).reshape(3, 3)
print(a, '\n')
# 按行进行索引排序,返回排序好的数值在该行的索引
print(np.argsort(a, axis=1), '\n')
# 按列进行索引排序
print(np.argsort(a, axis=0))
结果
[[6.79752461 7.3727076 2.16523161]
[1.14164138 8.26044896 1.08036863]
[2.14832383 6.11497858 5.64668565]]
[[2 0 1]
[2 0 1]
[0 2 1]]
[[1 2 1]
[2 0 0]
[0 1 2]]