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]

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏Python爬虫实战

MySQL从零开始:05 MySQL数据类型

距离上次更新 MySQL 从零开始系列,已经过去了十几天,时间隔得有点长,由于我选用的是 MySQL 的最新版本,网上的教程大多停留在 MySQL 5.x,所以...

1013
来自专栏Java呓语

第9章、语言结构

字符串是包含在单引号(')或双引号(")字符中的字节或字符序列。 以下几行例子是等同的:

683
来自专栏与神兽党一起成长

[MySQL]查询学生选课的情况(一)

这是我工作遇到的问题,现在自己设计一个简化的类似场景,现实中这样的数据表设计可能有很多不合理的地方。 首先看表结构:

785
来自专栏PPV课数据科学社区

【学习】七天搞定SAS(二):基本操作(判断、运算、基本函数)

SAS生成新变量 SAS支持基本的加减乘除,值得一提的是它的**代表指数,而不是^。 * Modify homegarden data set with ass...

3534
来自专栏ml

hdu----(5023)A Corrupt Mayor's Performance Art(线段树区间更新以及区间查询)

A Corrupt Mayor's Performance Art Time Limit: 2000/1000 MS (Java/Others)    Memo...

3349
来自专栏向治洪

数据结构之链表

一、概念 (1)数组的线性序是由数组的下标决定的,链表中的顺序是由各对象中的指针所决定的 (2)链表结点结构 node *prev; node *next; i...

18310
来自专栏我的博客

ES中的查询

一、查询语句形式 1.叶子语句 2.复合语句(一条复合语句可以是多条叶子语句和多个复合语句组成) 二、查询和过滤的区别 1.过滤是将查询设置为是否匹配(只...

6028
来自专栏Java成神之路

PL/SQL学习笔记_01_基础:变量、流程控制

PL/SQL语句可以在Oracle客户端的 SQL窗口或者 command  窗口中运行

652
来自专栏landv

excel_VB宏脚本_批量生成点餐宝接受的格式

1112
来自专栏数据结构与算法

POJ1509 Glass Beads(最小表示法 后缀自动机)

Once upon a time there was a famous actress. As you may expect, she played mostl...

701

扫码关注云+社区