首页 > > > 干货 | 50题带你玩转numpy
这是在stackoverflow和numpy文档里汇总的numpy练习题,目的是为新老用户提供快速参考。

np (★☆☆)np
import numpy as npprint(np.__version__)
np.show_config()Z = np.zeros(10)
print(Z)Z = np.zeros((10,10))
print("%d bytes" % (Z.size * Z.itemsize))%run `python -c "import numpy; numpy.info(numpy.add)"`Z = np.zeros(10)
Z[4] = 1
print(Z)Z = np.arange(10,50)
print(Z)Z = np.arange(50)
Z = Z[::-1]
print(Z)Z = np.arange(9).reshape(3,3)
print(Z)nz = np.nonzero([1,2,,,4,])
print(nz)Z = np.eye(3)
print(Z)Z = np.random.random((3,3,3))
print(Z)Z = np.random.random((10,10))
Zmin, Zmax = Z.min(), Z.max()
print(Zmin, Zmax)Z = np.random.random(30)
m = Z.mean()
print(m)Z = np.ones((10,10))
Z[1:-1,1:-1] =
print(Z)Z = np.ones((5,5))
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=)
print(Z)print( * np.nan)
print(np.nan == np.nan)
print(np.inf > np.nan)
print(np.nan - np.nan)
print(np.nan in set([np.nan]))
print(0.3 == 3 * 0.1)Z = np.diag(1+np.arange(4),k=-1)
print(Z)Z = np.zeros((8,8),dtype=int)
Z[1::2,::2] = 1
Z[::2,1::2] = 1
print(Z)print(np.unravel_index(99,(6,7,8)))Z = np.tile( np.array([[,1],[1,]]), (4,4))
print(Z)Z = np.random.random((5,5))
Z = (Z - np.mean (Z)) / (np.std (Z))
print(Z)color = np.dtype([("r", np.ubyte, 1),
("g", np.ubyte, 1),
("b", np.ubyte, 1),
("a", np.ubyte, 1)])Z = np.dot(np.ones((5,3)), np.ones((3,2)))
print(Z)
# Alternative solution, in Python 3.5 and above
Z = np.ones((5,3)) @ np.ones((3,2))
print(Z)# Author: Evgeni Burovski
Z = np.arange(11)
Z[(3 < Z) & (Z <= 8)] *= -1
print(Z)
# Author: Jake VanderPlas
print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))Z**Z
2 << Z >> 2
Z <- Z
1j*Z
Z/1/1
Z<Z>Zprint(np.array() / np.array())
print(np.array() // np.array())
print(np.array([np.nan]).astype(int).astype(float))# Author: Charles R Harris
Z = np.random.uniform(-10,+10,10)
print (np.copysign(np.ceil(np.abs(Z)), Z))Z1 = np.random.randint(,10,10)
Z2 = np.random.randint(,10,10)
print(np.intersect1d(Z1,Z2))# Suicide mode on
defaults = np.seterr(all="ignore")
Z = np.ones(1) /
# Back to sanity
_ = np.seterr(**defaults)An equivalent way, with a context manager:
with np.errstate(divide='ignore'):
Z = np.ones(1) / np.sqrt(-1) == np.emath.sqrt(-1)yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
today = np.datetime64('today', 'D')
tomorrow = np.datetime64('today', 'D') + np.timedelta64(1, 'D')Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]')
print(Z)A = np.ones(3)*1
B = np.ones(3)*2
C = np.ones(3)*3
np.add(A,B,out=B)
np.divide(A,2,out=A)
np.negative(A,out=A)
np.multiply(A,B,out=A)Z = np.random.uniform(,10,10)
print (Z - Z%1)
print (np.floor(Z))
print (np.ceil(Z)-1)
print (Z.astype(int))
print (np.trunc(Z))Z = np.zeros((5,5))
Z += np.arange(5)
print(Z)def generate():
for x in range(10):
yield x
Z = np.fromiter(generate(),dtype=float,count=-1)
print(Z)Z = np.linspace(,1,11,endpoint=False)[1:]
print(Z)Z = np.random.random(10)
Z.sort()
print(Z)# Author: Evgeni Burovski
Z = np.arange(10)
np.add.reduce(Z)A = np.random.randint(,2,5)
B = np.random.randint(,2,5)
# Assuming identical shape of the arrays and a tolerance for the comparison of values
equal = np.allclose(A,B)
print(equal)
# Checking both the shape and the element values, no tolerance (values have to be exactly equal)
equal = np.array_equal(A,B)
print(equal)Z = np.zeros(10)
Z.flags.writeable = False
Z[] = 1Z = np.random.random((10,2))
X,Y = Z[:,], Z[:,1]
R = np.sqrt(X**2+Y**2)
T = np.arctan2(Y,X)
print(R)
print(T)Z = np.random.random(10)
Z[Z.argmax()] =
print(Z)x and y coordinates covering the [0,1]x[0,1] area (★★☆)Z = np.zeros((5,5), [('x',float),('y',float)])
Z['x'], Z['y'] = np.meshgrid(np.linspace(,1,5),
np.linspace(,1,5))
print(Z)# Author: Evgeni Burovski
X = np.arange(8)
Y = X + 0.5
C = 1.0 / np.subtract.outer(X, Y)
print(np.linalg.det(C))for dtype in [np.int8, np.int32, np.int64]:
print(np.iinfo(dtype).min)
print(np.iinfo(dtype).max)
for dtype in [np.float32, np.float64]:
print(np.finfo(dtype).min)
print(np.finfo(dtype).max)
print(np.finfo(dtype).eps)np.set_printoptions(threshold=np.nan)
Z = np.zeros((16,16))
print(Z)Z = np.arange(100)
v = np.random.uniform(,100)
index = (np.abs(Z-v)).argmin()
print(Z[index])本文翻译自:https://github.com/rougier/numpy-100

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31537575/viewspace-3162994/ ,如需转载,请注明出处,否则将追究法律责任。