Numpy练习

1. Import the numpy package under the name np

import numpy as np

2. Print the numpy version and the configuration

print np.__version__
# np.show_config()
1.10.4

3. Create a null vector of size 10

E = np.empty(3) # not zero acturally
Z = np.zeros(10)
print(Z)
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]

4. How to get the documentation of the numpy add function from the command line ?

!python -c"import numpy; numpy.info(numpy.add)"
add(x1, x2[, out])

Add arguments element-wise.

Parameters
----------
x1, x2 : array_like
    The arrays to be added.  If ``x1.shape != x2.shape``, they must be
    broadcastable to a common shape (which may be the shape of one or
    the other).

Returns
-------
add : ndarray or scalar
    The sum of `x1` and `x2`, element-wise.  Returns a scalar if
    both  `x1` and `x2` are scalars.

Notes
-----
Equivalent to `x1` + `x2` in terms of array broadcasting.

Examples
--------
>>> np.add(1.0, 4.0)
5.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.add(x1, x2)
array([[  0.,   2.,   4.],
       [  3.,   5.,   7.],
       [  6.,   8.,  10.]])

5. Create a null vector of size 10 but the fifth value which is 1

Z = np.zeros(10)
Z[4] = 1 # index just like list
print(Z)
[ 0.  0.  0.  0.  1.  0.  0.  0.  0.  0.]

6. Create a vector with values ranging from 10 to 49

V = np.arange(10,50) # np.arange not np.range
print(V)
[10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49]

7. Reverse a vector (first element becomes last)

V = np.arange(5)
V = V[::-1]
print(V)
[4 3 2 1 0]

8. Create a 3x3 matrix with values ranging from 0 to 8

A = np.arange(9).reshape(3,3)
print(A)
[[0 1 2]
 [3 4 5]
 [6 7 8]]

9. Find indices of non-zero elements from [1,2,0,0,4,0]

arr = np.array([1,2,0,0,4,0])
# list comprehension is not consise VS nonzero
nz1 = [i for i in range(len(arr)) if arr[i]==0] # a list
nz = np.nonzero(arr) # return a tuple
print nz
print nz1
(array([0, 1, 4]),)
[2, 3, 5]

10. Create a 3x3 identity matrix

A = np.eye(3) # for indentity matrix
B = np.identity(3) # or identity
print A
print B == A
[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]
[[ True  True  True]
 [ True  True  True]
 [ True  True  True]]

11. Create a 3x3x3 array with random values

Z = np.random.random((3,3,3))
print Z
[[[ 0.37802182  0.51185549  0.09273136]
  [ 0.35946865  0.44674969  0.76084106]
  [ 0.95776962  0.35601145  0.8915905 ]]

 [[ 0.39016786  0.63052983  0.20385571]
  [ 0.04379682  0.32062423  0.97007016]
  [ 0.4026562   0.76746884  0.84974329]]

 [[ 0.85230695  0.6368344   0.42200517]
  [ 0.98098412  0.24666028  0.86381806]
  [ 0.71310323  0.89115971  0.85823333]]]

12. Create a 10x10 array with random values and find the minimum and maximum values

Z = np.random.random((10,10))
z_max, z_min = Z.max(), Z.min()
# z_max, z_min = np.max(Z), np.min(Z)
print z_max
print z_min
0.996975591901
0.0148123771689

13. Create a random vector of size 30 and find the mean value

Z = np.random.random(10)
m = Z.mean()
# m = np.mean(Z)
print m
0.499048171998

14. Create a 2d array with 1 on the border and 0 inside

Z = np.ones((5,5))
Z[1:-1, 1:-1] = 0 # indexing
print Z
[[ 1.  1.  1.  1.  1.]
 [ 1.  0.  0.  0.  1.]
 [ 1.  0.  0.  0.  1.]
 [ 1.  0.  0.  0.  1.]
 [ 1.  1.  1.  1.  1.]]

15. What is the result of the following expression ?

0*np.nan #nan
nan
np.nan == np.nan
False
np.inf > np.nan
False
np.nan - np.nan
nan
0.3 == 3 * 0.1
False

16. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal

Z = np.diag(1+np.arange(4), k=-1)
print Z
[[0 0 0 0 0]
 [1 0 0 0 0]
 [0 2 0 0 0]
 [0 0 3 0 0]
 [0 0 0 4 0]]

17. Create a 8x8 matrix and fill it with a checkerboard pattern

Z = np.zeros((8,8),dtype=int)
Z[1::2,0::2]=1
Z[0::2,1::2]=1
print Z
[[0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]]

18. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element ?

print np.unravel_index(100,(6,7,8))
(1, 5, 4)

19. Create a checkerboard 8x8 matrix using the tile function

Z = np.tile(np.array([[0,1],[1,0]]), (4,4))
print Z
[[0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]]

20. Normalize a 5x5 random matrix

Z = np.random.random((5,5))
z_max, z_min = Z.max(), Z.min()
Z = (Z - z_min)/(z_max - z_min)
print Z
[[ 0.35432088  0.9860153   0.73550363  0.30350038  0.10499184]
 [ 0.22329659  0.          0.54464366  0.99324627  0.98878285]
 [ 0.4801603   0.08399077  0.43971682  0.71831189  0.79786892]
 [ 1.          0.12234266  0.99166839  0.64018204  0.27405883]
 [ 0.68890375  0.26652723  0.97298099  0.94534027  0.58056662]]

21. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product)

A = np.ones((5,3))
B = np.ones((3,2))
print np.dot(A,B) #or A.dot(B)
[[ 3.  3.]
 [ 3.  3.]
 [ 3.  3.]
 [ 3.  3.]
 [ 3.  3.]]

22. Given a 1D array, negate all elements which are between 3 and 8, in place

Z = np.arange(11)
Z[(3 < Z) & (Z <= 8)] *= -1 # boolean index
print Z
[ 0  1  2  3 -4 -5 -6 -7 -8  9 10]

23. Create a 5x5 matrix with row values ranging from 0 to 4

Z = np.zeros((5,5))
Z += np.arange(5) # matrix + row
print Z
[[ 0.  1.  2.  3.  4.]
 [ 0.  1.  2.  3.  4.]
 [ 0.  1.  2.  3.  4.]
 [ 0.  1.  2.  3.  4.]
 [ 0.  1.  2.  3.  4.]]

24. Consider a generator function that generates 10 integers and use it to build an array

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

Z = np.fromiter(generate(), dtype=float, count=-1)
print Z    
[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.]

25. Create a vector of size 10 with values ranging from 0 to 1, both excluded

Z = np.linspace(0,1,num=12,endpoint=True)[1:-1]
print Z
[ 0.09090909  0.18181818  0.27272727  0.36363636  0.45454545  0.54545455
  0.63636364  0.72727273  0.81818182  0.90909091]

26. Create a random vector of size 10 and sort it

Z = np.random.random(10)
Z.sort()
print Z
[ 0.02092486  0.10778371  0.1580741   0.17828872  0.28058869  0.63512671
  0.70412522  0.84783555  0.93924023  0.98453489]

27. How to sum a small array faster than np.sum ?

Z = np.arange(10)
%timeit np.sum(Z)
%timeit np.add.reduce(Z)
The slowest run took 21.24 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 2.08 µs per loop
The slowest run took 10.39 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.15 µs per loop

28. Consider two random array A anb B, check if they are equal

A = np.random.randint(0,2,5)
B = np.random.randint(0,2,5)
equal = np.allclose(A,B)
#Returns True if two arrays are element-wise equal within a tolerance.
print equal
False

29. Make an array immutable (read-only)

Z = np.zeros(10, dtype='int')
Z.flags.writeable = False
# Z[0] = 1 raise ValueError

30. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates

Z = np.random.random((10,2))
X, Y = Z[:,0], Z[:,1]
R = np.sqrt(X**2 + Y**2)
T = np.arctan2(Y,X)
print R
print T
[ 0.97581795  0.59808053  0.4108556   0.53083869  0.27302014  0.36028763
  0.88051885  0.89321379  1.17598494  0.95036096]
[ 0.49590473  1.55488672  1.42839068  0.06888012  0.22952511  0.71644146
  0.48692754  0.42476661  0.85430172  1.30708871]

31. Create random vector of size 10 and replace the maximum value by 0

Z = np.random.random(10)
Z[Z.argmax()] = 0 # Z.argmax()
print Z
[ 0.79605583  0.          0.43405045  0.74944543  0.87654654  0.04885993
  0.03266925  0.09662387  0.86090177  0.48594978]

32. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area

Z = np.zeros((10,10), [('x',float),('y',float)])
Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,10),
                             np.linspace(0,1,10))

33. Print the minimum and maximum representable value for each numpy scalar type

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)
-128
127
-2147483648
2147483647
-9223372036854775808
9223372036854775807
-3.40282e+38
3.40282e+38
1.19209e-07
-1.79769313486e+308
1.79769313486e+308
2.22044604925e-16

34. How to find the closest value (to a given scalar) in an array ?

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

35. Create a structured array representing a position (x,y) and a color (r,g,b)

 Z = np.zeros(10, [ ('position', [ ('x', float, 1),
                                   ('y', float, 1)]),
                    ('color',    [ ('r', float, 1),
                                   ('g', float, 1),
                                   ('b', float, 1)])])
print Z
[((0.0, 0.0), (0.0, 0.0, 0.0)) ((0.0, 0.0), (0.0, 0.0, 0.0))
 ((0.0, 0.0), (0.0, 0.0, 0.0)) ((0.0, 0.0), (0.0, 0.0, 0.0))
 ((0.0, 0.0), (0.0, 0.0, 0.0)) ((0.0, 0.0), (0.0, 0.0, 0.0))
 ((0.0, 0.0), (0.0, 0.0, 0.0)) ((0.0, 0.0), (0.0, 0.0, 0.0))
 ((0.0, 0.0), (0.0, 0.0, 0.0)) ((0.0, 0.0), (0.0, 0.0, 0.0))]

36. Consider a random vector with shape (100,2) representing coordinates, find point by point distances

Z = np.random.random((10,2))
X,Y = np.atleast_2d(Z[:,0]), np.atleast_2d(Z[:,1])
D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
import scipy
import scipy.spatial
Z = np.random.random((10,2))
D = scipy.spatial.distance.cdist(Z,Z)
# print D

37. How to convert a float (32 bits) array into an integer (32 bits) in place ?

Z = np.arange(10,dtype=np.float32)
Z = Z.astype(np.int32,copy=False) #astype
print(Z)
[0 1 2 3 4 5 6 7 8 9]

38. Consider the following file,How to read it ?

1,2,3,4,5
6,,,7,8
,,9,10,11

Z = np.genfromtxt('missing.dat',delimiter=",")
print Z
[[  1.   2.   3.   4.   5.]
 [  6.  nan  nan   7.   8.]
 [ nan  nan   9.  10.  11.]]

39. What is the equivalent of enumerate for numpy arrays ?

Z = np.arange(9).reshape(3,3)
for index,value in np.ndenumerate(Z):
    print(index,value)
((0, 0), 0)
((0, 1), 1)
((0, 2), 2)
((1, 0), 3)
((1, 1), 4)
((1, 2), 5)
((2, 0), 6)
((2, 1), 7)
((2, 2), 8)
for index in np.ndindex(Z.shape):
    print(index,Z[index])
((0, 0), 0)
((0, 1), 1)
((0, 2), 2)
((1, 0), 3)
((1, 1), 4)
((1, 2), 5)
((2, 0), 6)
((2, 1), 7)
((2, 2), 8)

40. Generate a generic 2D Gaussian-like array

X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
D = np.sqrt(X*X+Y*Y)
sigma, miu = 1.0, 0.0
G = np.exp((D-miu)**2/(2.0*sigma**2))

41. How to randomly place p elements in a 2D array ?

n = 10
p = 3
Z = np.zeros((n,n))
index = np.random.choice(np.arange(n*n),p,replace=False)
np.put(Z,index,1)
Z
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])

41. How to I sort an array by the nth column ?

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

42. Subtract the mean of each row of a matrix

X = np.random.randint(4,size=(2,3))
print X
Y = X - X.mean(axis=1, keepdims=True)
print Y
[[2 2 1]
 [1 1 1]]
[[ 0.33333333  0.33333333 -0.66666667]
 [ 0.          0.          0.        ]]

43. How to tell if a given 2D array has null columns ?

# numpy.any(a, axis=None, out=None, keepdims=False)
# Test whether any array element along a given axis evaluates to True.
Z = np.random.randint(0,3,(3,10))
print (~Z.any(axis=0)).any()
True

44. Find the nearest value from a given value in an array

# numpy.ndarray.flat
# A 1-D iterator over the array.
# This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of, Python’s built-in iterator object.
Z = np.random.uniform(0,1,10)
z = 0.5
m = Z.flat[np.abs(Z-z).argmin()]
print m
0.494656507792

45. How to swap two rows of an array ?

A = np.arange(25).reshape(5,5)
A[[0,1]] = A[[1,0]]
print A
[[ 5  6  7  8  9]
 [ 0  1  2  3  4]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]

46. How to find the most frequent value in an array ?

# np.bincount()
# Count number of occurrences of each value in array of non-negative ints.
Z = np.random.randint(0,5,10)
print Z
print np.bincount(Z)
print np.bincount(Z).argmax()
[1 0 4 1 1 2 0 1 2 3]
[2 4 2 1 1]
1

47. How to get the n largest values of an array?

# np.random.shuffle(x), Modify a sequence in-place
# np.argsort(x) Returns the indices that would sort an array.
# np.argpartition(x)
Z = np.arange(10)
np.random.shuffle(Z)
n = 2
print Z[np.argsort(Z)[-n:]] # slow
print Z[np.argpartition(-Z,n)[:n]] # fast
[8 9]
[9 8]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容

  • 我的老家在浙江省的温州市。今天我就跟你们来介绍下我们这边的年俗。 除尘是必不可少的,刚到家那天我...
    季妞阅读 537评论 2 4
  • 评价别人,要记住这点。每个人都在发展变化之中,被你蔑视的,说不定哪一天就翻云覆雨叱咤风云。被你尊重的,说不定哪天脱...
    玥玥粑粑阅读 201评论 1 0
  • 最近项目中购物车添加了商品数量的编辑功能,so问题来了,若我们编辑的商品cell位于tableview上方,那一切...
    mengshuobuyi阅读 540评论 -1 1