Numpy数组操作短代码

如何用一个生成10个整数的函数来构建数组

1
2
3
4
5
6
7
8
import numpy as np

def generate():
for x in range(10):
yield x

Z = np.fromiter(generate(), dtype=float, count=-1)
print (Z)

创建一个二维数组,其中边界值为1,其余值为0

1
2
3
4
5
import numpy as np

Z = np.ones((10,10))
Z[1:-1,1:-1] = 0
print(Z)

对于一个存在在数组,如何添加一个用0填充的边界

1
2
3
4
5
import numpy as np

Z = np.ones((5,5))
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
print(Z)

如何判断一个给定的二维数组存在空列

1
2
3
4
import numpy as np

Z = np.random.randint(0,3,(3,10))
print((~Z.any(axis=0)).any())

如何在二维数组的随机位置放置p个元素

1
2
3
4
5
6
7
import numpy as np

n = 10
p = 3
Z = np.zeros((n,n))
np.put(Z, np.random.choice(range(n*n), p, replace=False),1)
print(Z)

给定一个一维数组,对其在3到8之间的所有元素取反

1
2
3
4
5
import numpy as np

Z = np.arange(11)
Z[(3 < Z) & (Z <= 8)] *= -1
print(Z)

如何找出两个数组公共的元素

1
2
3
4
5
import numpy as np

Z1 = np.random.randint(0, 10, 10)
Z2 = np.random.randint(0, 10, 10)
print (np.intersect1d(Z1, Z2))

如何在数组中找到与给定标量接近的值

1
2
3
4
5
6
import numpy as np

Z = np.arange(100)
v = np.random.uniform(0, 100)
index = (np.abs(Z-v)).argmin()
print(Z[index])

如何找出数组中出现频率最高的值

1
2
3
4
import numpy as np

Z = np.random.randint(0, 10, 50)
print(np.bincount(Z).argmax())

如何找到一个数组的第n个最大值

1
2
3
4
5
6
7
8
9
10
11
import numpy as np

Z = np.arange(10000)
np.random.shuffle(Z)
n = 5

# Slow
print (Z[np.argsort(Z)[-n:]])

# Fast
print (Z[np.argpartition(-Z,n)[:n]])

如何对数组通过第n列进行排序

1
2
3
4
5
import numpy as np

Z = np.random.randint(0,10,(3,3))
print(Z)
print(Z[ Z[:,1].argsort() ])

如何对一个数组中任意两行做交换

1
2
3
4
5
import numpy as np

A = np.arange(25).reshape(5,5)
A[[0,1]] = A[[1,0]]
print(A)

如何知道一个数组的内存大小

1
2
3
4
import numpy as np

Z = np.zeros((10,10))
print("%d bytes" % (Z.size * Z.itemsize))