我的numpy100筆記

寫給自己的知識點記錄,向題庫作者和所有解答鏈接中的作者致敬

https://github.com/rougier/numpy-100/blob/master/100_Numpy_exercises_with_hints_with_solutions.md

import numpy as np

36. Extract the integer part of a random array using 5 different methods (★★☆)

提取整數(shù)部分的五種方法

Z = np.random.uniform(0,10,10)

print (Z - Z%1)
print (np.floor(Z))
print (np.ceil(Z)-1)
print (Z.astype(int))
print (np.trunc(Z))

38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)

def generate():
    for x in range(10):
        yield x
z = np.fromiter(generate(),dtype=float,count=-1)
print(z)

關(guān)于fromiter函數(shù)的格式和用法
https://blog.csdn.net/zouxiaolv/article/details/98872903

39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)

z=np.linspace(0,1,11,endpoint=False)[1:]

41. How to sum a small array faster than np.sum? (★★☆)

Z = np.arange(10)
np.add.reduce(Z)

42. Consider two random array A and B, check if they are equal (★★☆)

A = np.random.randint(0,2,5)
B = np.random.randint(0,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)

np.allclose()函數(shù),用來比較numpy數(shù)組每個位置元素是否相等
np.array_equal(A,B)函數(shù),

43. Make an array immutable (read-only) (★★☆)

Z = np.zeros(10)
Z.flags.writeable = False
Z[0] = 1

Z.flags.writeable = False

np.zeros函數(shù)的參數(shù)可以指定坐標(biāo)名稱和數(shù)據(jù)類型

45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)

Z = np.random.random(10)
Z[Z.argmax()] = 0
print(Z)

argmax,argmin返回最大最小值的索引

46. Create a structured array with 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(0,1,5),
                             np.linspace(0,1,5))
print(Z)

創(chuàng)建新結(jié)構(gòu)的數(shù)據(jù)

48. 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)

51. 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)

創(chuàng)建新的數(shù)據(jù)結(jié)構(gòu)

52. 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], Z[:,1])
D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
print(D)

# Much faster with scipy
import scipy
# Thanks Gavin Heverly-Coulson (#issue 1)
import scipy.spatial

Z = np.random.random((10,2))
D = scipy.spatial.distance.cdist(Z,Z)
print(D)

np.atleast_2d 將輸入數(shù)據(jù)直接視為2維
https://blog.csdn.net/qq_21950671/article/details/79856600

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

Z = (np.random.rand(10)*100).astype(np.float32)
Y = Z.view(np.int32)
Y[:] = Z
print(Y)

轉(zhuǎn)換數(shù)據(jù)類型

54. How to read the following file? (★★☆)

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

from io import StringIO

# Fake file
s = StringIO('''1, 2, 3, 4, 5

                6,  ,  , 7, 8

                 ,  , 9,10,11
''')
Z = np.genfromtxt(s, delimiter=",", dtype=np.int)
print(Z)

55. 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)

56. 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, mu = 1.0, 0.0
G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )
print(G)

57. How to randomly place p elements in a 2D array? (★★☆)

# Author: Divakar

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

random.choice函數(shù)
https://www.runoob.com/python/func-number-choice.html

59. How to sort an array by the nth column? (★★☆)

hint: argsort

# Author: Steve Tjoa

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

60. How to tell if a given 2D array has null columns? (★★☆)

hint: any, ~

# Author: Warren Weckesser

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

非和.any()函數(shù)的使用

62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆)

hint: np.nditer

A = np.arange(3).reshape(3,1)
B = np.arange(3).reshape(1,3)
it = np.nditer([A,B,None])
for x,y,z in it: z[...] = x + y
print(it.operands[2])

63. Create an array class that has a name attribute (★★☆)

hint: class method

class NamedArray(np.ndarray):
    def __new__(cls, array, name="no name"):
        obj = np.asarray(array).view(cls)
        obj.name = name
        return obj
    def __array_finalize__(self, obj):
        if obj is None: return
        self.info = getattr(obj, 'name', "no name")

Z = NamedArray(np.arange(10), "range_10")
print (Z.name)

64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★)

hint: np.bincount | np.add.at

# Author: Brett Olsen

Z = np.ones(10)
I = np.random.randint(0,len(Z),20)
Z += np.bincount(I, minlength=len(Z))
print(Z)

# Another solution
# Author: Bartosz Telenczuk
np.add.at(Z, I, 1)
print(Z)

關(guān)于add.at https://blog.csdn.net/sunny_ckyh/article/details/102383943
at(self, a, indices, b=None)函數(shù)執(zhí)行的操作為:
a[indices]+=b,并可以重復(fù)多次,最終可以達(dá)到統(tǒng)計indices所傳入的數(shù)組中每個元素的出現(xiàn)頻率,并相加到a中相對應(yīng)下標(biāo)位置的操作。

65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★)

hint: np.bincount

# Author: Alan G Isaac

X = [1,2,3,4,5,6]
I = [1,3,9,3,4,1]
F = np.bincount(I,X)
print(F)

關(guān)于np.bincount函數(shù)
https://www.cnblogs.com/Kaivenblog/p/10824529.html

https://blog.csdn.net/qq_42893334/article/details/104261619

66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★★)

hint: np.unique

# Author: Nadav Horesh

w,h = 16,16
I = np.random.randint(low=0,high=2,size=(h,w,3)).astype(np.ubyte)
F = I[...,0]*256*256 + I[...,1]*256 +I[...,2]
n = len(np.unique(F))
print(np.unique(I))

unique() 函數(shù)對于一維數(shù)組或列表返回的是一個無元素重復(fù)的數(shù)組或列表
示例:
https://blog.csdn.net/qq_39348113/article/details/82599631

68. Considering a one-dimensional vector D, how to compute means of subsets of D using a vector S of same size describing subset indices? (★★★)

hint: np.bincount

# Author: Jaime Fernández del Río

D = np.random.uniform(0,1,100)
S = np.random.randint(0,10,100)
D_sums = np.bincount(S, weights=D)
D_counts = np.bincount(S)
D_means = D_sums / D_counts
print(D_means)

# Pandas solution as a reference due to more intuitive code
import pandas as pd
print(pd.Series(D).groupby(S).mean())

69. How to get the diagonal of a dot product? (★★★)

hint: np.diag

# Author: Mathieu Blondel

A = np.random.uniform(0,1,(5,5))
B = np.random.uniform(0,1,(5,5))

# Slow version  
np.diag(np.dot(A, B))

# Fast version
np.sum(A * B.T, axis=1)

# Faster version
np.einsum("ij,ji->i", A, B)

71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★)

hint: array[:, :, None]

A = np.ones((5,5,3))
B = 2*np.ones((5,5))
print(A * B[:,:,None])

廣播,詳見
http://www.itdecent.cn/p/3c3f7da88516

72. How to swap two rows of an array? (★★★)

hint: array[[]] = array[[]]

# Author: Eelco Hoogendoorn

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

A[0,1]表示零行一列的元素,而A[[0,1]]表示第零行和第一行
列變換寫法為

A[:,[0,1]]=A[:,[1,0]]

參考
https://blog.csdn.net/xidianbaby/article/details/89373680

73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★)

hint: repeat, np.roll, np.sort, view, np.unique

# Author: Nicolas P. Rougier

faces = np.random.randint(0,100,(10,3))
F = np.roll(faces.repeat(2,axis=1),-1,axis=1)
F = F.reshape(len(F)*3,2)
F = np.sort(F,axis=1)
G = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] )
G = np.unique(G)
print(G)

numpy.roll
numpy.roll(a, shift, axis=None) 用于沿著指定的 axis 滾動數(shù)組元素。若不指定 axis,則所有元素依次滾動:
https://www.cnblogs.com/massquantity/p/10289480.html

74. Given an array C that is a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)

hint: np.repeat

# Author: Jaime Fernández del Río

C = np.bincount([1,1,2,3,4,4,6])
A = np.repeat(np.arange(len(C)), C)
print(A)

repeat可對不同位數(shù)分別進(jìn)行不同次數(shù)的復(fù)制

75. How to compute averages using a sliding window over an array? (★★★)

hint: np.cumsum

# Author: Jaime Fernández del Río

def moving_average(a, n=3) :
    ret = np.cumsum(a, dtype=float)
    ret[n:] = ret[n:] - ret[:-n]
    return ret[n - 1:] / n
Z = np.arange(20)
print(moving_average(Z, n=3))

cumsum函數(shù)用法,按給定軸返回包括中間步驟的累加和。
https://blog.csdn.net/yuansuo0516/article/details/78331568/
個人理解:累加和序列錯n位相減得到從每一位起向前共n位數(shù)的和,再除以n得到長度為n的“滑動窗口”在各個位置時窗內(nèi)的平均數(shù)。

77. How to negate a boolean, or to change the sign of a float inplace? (★★★)

hint: np.logical_not, np.negative

# Author: Nathaniel J. Smith

Z = np.random.randint(0,2,100)
np.logical_not(Z, out=Z)

Z = np.random.uniform(-1.0,1.0,100)
np.negative(Z, out=Z)

反轉(zhuǎn)符號

82. Compute a matrix rank (★★★)

hint: np.linalg.svd

# Author: Stefan van der Walt

Z = np.random.uniform(0,1,(10,10))
U, S, V = np.linalg.svd(Z) # Singular Value Decomposition
rank = np.sum(S > 1e-10)
print(rank)

詳解svd
https://www.cnblogs.com/daniel-D/p/3218063.html

81. Consider an array Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14], how to generate an array R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]]? (★★★)

hint: stride_tricks.as_strided

# Author: Stefan van der Walt

Z = np.arange(1,15,dtype=np.uint32)
R = stride_tricks.as_strided(Z,(11,4),(4,4))
print(R)

關(guān)于 np.stride_tricks.as_strided(x, shape, strides, subok, writeable) 函數(shù)的用法
https://zhuanlan.zhihu.com/p/64933417

86. Consider a set of p matrices wich shape (n,n) and a set of p vectors with shape (n,1). How to compute the sum of of the p matrix products at once? (result has shape (n,1)) (★★★)

hint: np.tensordot

# Author: Stefan van der Walt

p, n = 10, 20
M = np.ones((p,n,n))
V = np.ones((p,n,1))
S = np.tensordot(M, V, axes=[[0, 2], [0, 1]])
print(S)

# It works, because:
# M is (p,n,n)
# V is (p,n,1)
# Thus, summing over the paired axes 0 and 0 (of M and V independently),
# and 2 and 1, to remain with a (n,1) vector.

(0,2) 是對M而言,不是取第1,2軸,而是除去1,2 軸,所以要取的是第0軸
(0,1) 是對V而言,不是取第0,1軸,而是除去0,1 軸,所以要取的是第2軸
p個(n,n)矩陣和1個(p,n)矩陣分別相乘后的矩陣求和,分別寫入(p,1)的對應(yīng)位置即為結(jié)果

np.tensordot 的理解和使用:
https://blog.csdn.net/weixin_28710515/article/details/90230842

87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)

hint: np.add.reduceat

# Author: Robert Kern

Z = np.ones((16,16))
k = 4
S = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0),
                                       np.arange(0, Z.shape[1], k), axis=1)
print(S)

在兩個方向上分別按段求和
np.add.reduceat(x,list,axis):將矩陣按照list給定的節(jié)點劃分(每段含頭不含尾),并分段求和,axis=0時按行壓縮,axis=1時按列壓縮。
注:list序列應(yīng)是遞增的,若出現(xiàn)某一段開頭大于結(jié)尾則該段只有開頭的一位數(shù)。
https://blog.csdn.net/weixin_43584807/article/details/103095888

92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★)

hint: np.power, *, np.einsum

# Author: Ryan G.

x = np.random.rand(int(5e7))

%timeit np.power(x,3)
%timeit x*x*x
%timeit np.einsum('i,i,i->i',x,x,x)

計時結(jié)果:
3.79 s ± 1.21 s per loop (mean ± std. dev. of 7 runs, 1 loop each)
415 ms ± 3.36 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
246 ms ± 6.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

93. Consider two arrays A and B of shape (8,3) and (2,2). How to find rows of A that contain elements of each row of B regardless of the order of the elements in B? (★★★)

hint: np.where

# Author: Gabe Schwartz

A = np.random.randint(0,5,(8,3))
B = np.random.randint(0,5,(2,2))

C = (A[..., np.newaxis, np.newaxis] == B)
rows = np.where(C.any(axis=(3,1)).all(1))[0]
print(rows)

...省略,占位符,用于選擇符合某一索引條件的所有組
any或all可以指定軸“壓縮”

95. Convert a vector of ints into a matrix binary representation (★★★)

hint: np.unpackbits

# Author: Warren Weckesser

I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])
B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)
print(B[:,::-1])

# Author: Daniel T. McDonald

I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8)
print(np.unpackbits(I[:, np.newaxis], axis=1))

借助按位與運算可以比較討巧的完成二進(jìn)制轉(zhuǎn)換,但這種方法只能用于2( 4,16...)進(jìn)制
https://www.cnblogs.com/anno-ymy/p/11232454.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容