python创建一个类似于国家象棋棋盘的0-1矩阵_NumPy练习题(全中文并附详细讲解)...
100道 numpy 練習
1. Import the numpy package under the name np (★☆☆)')
導入numpy模塊,設置別稱為np
import numpy as np
2. Print the numpy version and the configuration (★☆☆)')
顯示numpy的版本號和配置文件
print(np.__version__)
np.show_config()
3. Create a null vector of size 10 (★☆☆)')
創建一個大小為10的空向量
# np.empty 構造一個大小為 shape 的未初始化數組,
# np.zeros 構造一個大小為 shape 的全0數組,
# np.ones 構造一個大小為 shape 的全1數組,
# np.ones 構造一個大小為 shape 的全1數組,
# np.full 構造一個大小為 shape 的用指定值填滿的數組,
#
print(np.empty(10))
print(np.zeros(10))
print(np.full((2,3),5.0))
4. How to find the memory size of any array (★☆☆)')
查看數組占用內存大小
# hint 每個元素點用內存大小乘以元素個數
sample4_1 = np.empty((3, 2), np.uint32)
sample4_2 = np.empty((3, 2), np.float16)
print(sample4_1.itemsize * sample4_1.size)
print(sample4_2.itemsize * sample4_2.size)
5. How to get the documentation of the numpy add function from the command line? (★☆☆)')
查看numpy中add函數的用法
# hint 使用 np.info函數可以查詢函數,類,模塊的文檔
np.info(np.add)
6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)')
創建一個大小為10的空向量,將第5個值設為1
sample = np.zeros(10)
sample[4] = 1
print(sample)
7. Create a vector with values ranging from 10 to 49 (★☆☆)')
用10到49的序列構建一個向量
sample2 = np.arange(10, 50) # arange 同樣不包含stop的值。
print(sample2)
8. Reverse a vector (first element becomes last) (★☆☆)')
將一個數組變換倒序(最后一個元素成為第一個元素)
# hint 這里是python的切片[起:止:間隔]
# print(np.arange(10)[::1]) 正常輸出
# print(np.arange(10)[0::1]) 與上面相同
# print(np.arange(10)[1::1]) 從第二個元素開始到最后一個
# print(np.arange(10)[1::-1]) 從第二個元素開始倒序輸出
# print(np.arange(10)[::-2]) 從最后一個元素起,間隔一個輸出
print(np.arange(10))
print(np.arange(10)[::-1])
9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)')
用0-8這9個數構造一個3x3大小的矩陣
# reshape 可以允許有一個參數為-1 ,系統會依據元素個數進行換算
sample3 = np.arange(9).reshape((3, -1))
print(sample3)
10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)')
從數組[1,2,0,0,4,0]中找出非0元素的下標
print(np.nonzero([1, 2, 0, 0, 4, 0]))
11. Create a 3x3 identity matrix (★☆☆)')
創建3x3的對角矩陣
# identity 只能創建方陣,eye要靈活一些,可以創建NxM的矩陣,也可以控制對角線的位置
print(np.identity(3))
print(np.eye(3,3,0)) #默認第一個和第二個參數相等,第三個參數為對角線位置
12. Create a 3x3x3 array with random values (★☆☆)')
用隨機數創建一個3x3x3的矩陣
print(np.random.random((3, 3, 3)))
13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)')
創建一個10x10的隨機數矩陣,并找到最大值和最小值
sample13 = np.random.random((10, 10))
print(sample13)
print(sample13.max(), np.min(sample13))
14. Create a random vector of size 30 and find the mean value (★☆☆)')
創建一個大小為30的數組,并計算其算術平均值
# mean計算算術平均值 average 計算加權平均值np.average(np.arange(1, 11) , weights=np.arange(10, 0, -1))
print(np.random.random(30).mean())
```python
## 15. Create a 2d array with 1 on the border and 0 inside (★☆☆)')
## 創建一個二維數組,邊為1,其余為0
```python
# hint [1:-1,1:-1]表示切出了芯。
sample15 = np.ones((5, 5))
print(sample15)
sample15[1:-1, 1:-1] = 0
print(sample15)
16. How to add a border (filled with 0s) around an existing array? (★☆☆)')
擴展給定數組的邊界
# hint pad 函數 有幾種mode
sample16 = np.ones((4,4))
print(np.pad(sample16, 1, mode='constant', constant_values=0))
17. What is the result of the following expression? (★☆☆)')
指出下列表達式的結果是什么?
# nan的意思是Not a Number nan的類型是float64
print(0 * np.nan) # nan 有nan參與的運算, 其結果也一定是nan
print(np.nan - np.nan) # nan
print(np.nan == np.nan) # False nan不是數,所以無法進行比較運算
print(np.nan > np.nan) # False
print(np.nan in {np.nan}) # True nan在nan的字典中
print(0.3 == 3 * 0.1) # False 浮點數可以比大小,但相等要用math.isclose比較
import math
print(math.isclose(0.3, 3 * 0.1)) # True
18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)')
用1,2,3,4做為對角線的下移一行,來創建5x5的矩陣
# hint diag函數的第二個參數指定對角線的位置
print(np.diag([1, 2, 3, 4], -1))
19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)')
創建一個類似國際象棋棋盤的8x8的矩陣
sample19 = np.zeros((8, 8))
sample19[::2, ::2] = 1
sample19[1::2, 1::2] = 1
print(sample19)
20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element?(★☆☆)')
對一個6x7x8的數組,找出第100個元素的下標
# hint unravel 這個函數非常難以理解,特別是第一個參數為向量時。
print(np.unravel_index(100, (6, 7, 8)))
21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)')
使用tile函數創建一個棋盤
print(np.tile([[0, 1], [1, 0]], (4, 4)))
22. Normalize a 5x5 random matrix (★☆☆)')
歸一化一個5x5的隨機矩陣
sample22 = np.random.random((5,5))*10
print(sample22)
print((sample22 - sample22.mean()) / sample22.std()) # std 計算均方差
23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)')
自定義一個用 unsigned bytes 表示RGBA顏色的dtype類型
# hint np.dtype
print(np.dtype([('R', np.ubyte), ('G', np.ubyte), ('B', np.ubyte), ('A', np.ubyte)]))
24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)')
計算5x3和3x2矩陣的內積(點乘)
# multiply(*) dot(@) matmul 這三個函數注意區分
sample24_1 = np.random.randint(0, 9, (5, 3))
sample24_2= np.random.randint(0, 9, (3, 2))
print(np.dot(sample24_1,sample24_2))
print(sample24_1 @ sample24_2)
25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)')
反轉一維數組中大于3小于8的所有元素
sample25 = np.arange(2, 12)
sample25[(sample25 >3) & (sample25 <8)] *= -1 # 使用& 表示 and
print(sample25)
26. What is the output of the following script? (★☆☆)')
指出下列程序的輸出?
# Author: Jake VanderPlas
print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))
print(sum(range(5), -1)) # sum(range(5)) + (-1)
print(np.sum(range(5),-1)) # 在選定的軸上執行求和。如果是默認值(axis=None),就會在所有的軸上執行求和。axis可以是負數,負數的話就代表倒著數的意思,和列表索引訪問差不多(N表示第N個,-N表示倒數第N個(沒有倒數第0個))
27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)')
對于整數向量,下面的哪些表達式是合法的?
Z = np.random.choice(10, 4)
Z**Z
2 << Z >> 2
Z
1j*Z
Z/1/1
ZZ # 使用 any 或 all
28. What are the result of the following expressions?(★☆☆)')
下面的表達式的結果是?
python np.array(0) / np.array(0) # 0 除法 np.array(0) // np.array(0) # 0 除法 np.array([np.nan]).astype(int).astype(float)
29. How to round away from zero a float array ? (★☆☆)')
對于浮點數數組取整??
# (**hint**: np.random.uniform(給定形狀產生隨機數組), np.copysign, np.ceil, np.abs)
sample29 =np.random.uniform(-10,10 ,10)
print(sample29)
print(np.ceil(np.copysign(sample29,np.ones(10))))
print(np.ceil(np.abs(sample29)))
30. How to find common values between two arrays? (★☆☆)')
查找兩個數組的交集?
print(np.intersect1d([1, 2, 3], [4, 2, 1]))
31. How to ignore all numpy warnings (not recommended)? (★☆☆)')
忽略numpy的警告?
defaults = np.seterr(all="ignore")
32. Is the following expressions true? (★☆☆)')
下列表達式結果為真么? (★☆☆)')
# np.sqrt(-1) # 出現警告
np.emath.sqrt(-1) #emath自動域數學函數 擴展到復數
33. How to get the dates of yesterday, today and tomorrow? (★☆☆)')
獲取今天,昨天,明天的日期?
# 從NumPy 1.7開始,有核心數組數據類型本身支持日期時間功能。 數據類型稱為“datetime64”,因為“datetime”已被Python中包含的日期時間庫占用。
yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
today = np.datetime64('today', 'D')
tomorrow = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
print(yesterday,today,tomorrow)
34. How to get all the dates corresponding to the month of July 2016? (★★☆)')
獲取2016年7月的所有日期?
Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]')
print(Z)
35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)')
避免復制操作來計算 ((A+B)*(-A/2)) ?
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)
print(np.multiply(A, B, out=A))
sample35_1 = np.arange(0, 10).reshape(2, 5)
sample35_2 = np.arange(10, 0, -1).reshape(2, 5)
sample35_r = np.empty((2, 5))
print(sample35_1)
print(sample35_2)
np.multiply(np.add(sample35_1, sample35_2), np.divide(np.negative(sample35_1), 2), out=sample35_r)
print(sample35_r)
36. Extract the integer part of a random array using 5 different methods (★★☆)')
用五種方法抽取隨機矩陣的整數部分(只想到一種)
Z = np.random.uniform(0,10,(10,10))
print(Z-Z%1)
print (np.floor(Z))
print (np.ceil(Z)-1)
print (Z.astype(int))
print (np.trunc(Z))
37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)')
創建一個5x5每行為0到4的矩陣
print(np.tile(np.arange(5), (5, 1)))
38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)')
使用生成器創建一個大小為10的數組
def gen(num):
seed = 0
for i in range(num):
yield seed
seed +=4
return seed
print(np.array([x for x in gen(10)]))
39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)')
創建一個大小為10的數組,值為0到1之間,不包含0和1
print(np.linspace(0, 1, 11, False)[1:])
40. Create a random vector of size 10 and sort it (★★☆)')
創建一個大小為10的數組并排序
sample40 = np.random.randint(0, 9, 10)
sample40.sort()
print(sample40)
41. How to sum a small array faster than np.sum? (★★☆)')
對一個小數組用比np.sum快的方法求和?
# hint
sample41 = np.arange(0,20)
print(np.add.reduce(sample41))
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)
equal = np.allclose(A,B) #默認在1e-05的誤差范圍內,比較兩個array是不是每一元素都相等
print(equal)
equal = np.array_equal(A,B) # 比較兩個數組是否相等
print(equal)
43. Make an array immutable (read-only) (★★☆)')
創建一個不可變數組(只讀)
Z = np.zeros(10)
Z.flags.writeable = False
用戶可以更改 WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED 這四個標志 Z[0] =1 # 報錯:ValueError: assignment destination is read-only
44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)')
創建一個大小為10x2的矩陣來代表笛卡兒坐標,并轉
cart = np.random.random((10, 2))
#
# vstack hstack column_stack
polar = np.column_stack((np.sqrt(np.add.reduce(np.square(cart), axis=1)), np.arctan(np.divide.reduce(cart, axis=1))))
print(cart, '\n\n', polar)
Z = cart
X, Y = Z[:, 0], Z[:, 1]
R = np.sqrt(X ** 2 + Y ** 2)
T = np.arctan2(Y, X) # arctan2 和 archtan的區別
print(np.column_stack((R, T)))
45. Create a random vector of size 10 and replace the maximum value by 0 (★★☆)')
創建一個大小為10的數組并把最大值設為0
sample45 = np.random.uniform(0,9,10)
print(sample45)
sample45[sample45.argmax()] =0
print(sample45)
46. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area')
創建一個xy的數組結構,包含[0,1]x[
# hint np.meshgrid 這個函數沒有理解
x = y = 5
nx = np.linspace(0, 1, x)
ny = np.linspace(0, 1, y)
xx, yy = np.meshgrid(nx, ny)
print(xx,yy)
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)
47. Given two arrays, X and Y, construct the Cauchy matrix(柯西矩陣) C (Cij =1/(xi - yj))(★☆☆)')
給定array X 和 Y, 構造柯西矩陣C (★☆☆)')
X = np.arange(3)
Y = X + 0.5
C = 1.0 / np.subtract.outer(X, Y)
print(np.linalg.det(C))
48. Print the minimum and maximum representable value for each numpy scalar type (★★☆)')
顯示機器能處理的數值的范圍
print(np.iinfo(np.int64))
print(np.iinfo(np.int32))
print(np.iinfo(np.uint16))
print(np.finfo(np.float64))
print(np.finfo(np.float16))
49. How to print all the values of an array? (★★☆)')
顯示array中所有的值
print(np.eye(10))
np.set_printoptions(threshold=100)
print(np.eye(40))
50. How to find the closest value (to a given scalar) in a vector? (★★☆)')
如何在向量中找到指定范圍的最近值?
sample50 = np.random.rand(4, 3) * 10
print(sample50)
print(np.argmin(sample50))
print(np.argmin(sample50, axis=0))
print(np.argmin(sample50, axis=1))
print(np.unravel_index(np.argmin(sample50), sample50.shape))
Z = np.arange(100)
v = np.random.uniform(0,100)
index = (np.abs(Z-v).argmin())
print(Z[index])
51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)')
構建一個代表位置 (x,y) 和 顏色 (r,g,b)的矩陣
mydtype = np.dtype([('xy',[('x', np.int64), ('y', np.int64)]), ('color',[('r', np.int16), ('g', np.int16), ('b', np.int16)])])
print(np.ones((3, 2), mydtype))
52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)')
用一個100*2的隨機向量來表示坐標,計算點到點的距離
Z = np.random.random((100,2))
X,Y = np.atleast_2d(Z[:,0], Z[:,1])
D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
print(D)
# 使用scipy處理速度快
# Thanks Gavin Heverly-Coulson (#issue 1)
import scipy.spatial
Z = np.random.random((100,2))
D = scipy.spatial.distance.cdist(Z,Z)
print(D)
53. How to convert a float (32 bits) array into an integer (32 bits) in place?(★☆☆)')
如何把一個浮點數組直接轉換
print((np.random.rand(20)*10).astype(np.int32,copy=False))
54. How to read the following file? (★★☆)')
從文本文件中讀取數據? (★★☆)')
txt 1, 2, 3, 4, 5 6, , , 7, 8 , , 9,10,11
from io import StringIO
s = StringIO("""1, 2, 3, 4, 5\n
6, , , 7, 8\n
, , 9,10,11\n""") # 模擬文件
print(np.genfromtxt(s,delimiter=','))
55. What is the equivalent of enumerate for numpy arrays? (★★☆)')
矩陣的坐標
for index ,x in np.ndenumerate(np.eye(3)):
print(index,x)
for index in np.ndindex(3,3):
print(index)
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)))
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax= fig.add_subplot(1, 3, 1, projection='3d')
suf=ax.plot_surface(X, Y, G, rstride=1, cstride=1, cmap='rainbow')
fig.colorbar(suf,shrink=0.5, aspect=5)
plt.subplot(132)
suf1 =plt.contourf(X,Y,G,8, alpha=.75, cmap='rainbow')
fig.colorbar(suf1,shrink=0.5, aspect=5)
# plt.show()
57. How to randomly place p elements in a 2D array? (★★☆)')
將元素P隨機的放入二維數組中
sample57 = np.ones((3, 10))
print(sample57)
np.put(sample57, np.arange(0, sample57.size), np.random.choice(100, sample57.size))
print(sample57)
58. Subtract the mean of each row of a matrix (★★☆)')
矩陣的第一行減去算術平均值
sample58 = np.random.rand(3,3)*10
print(sample58)
print(np.subtract(sample58,np.mean(sample58,axis=1,keepdims=True)))
59. How to sort an array by the nth column? (★★☆)')
把數組按第n列排序?
sample59 = np.random.randint(0, 9, (3, 5))
print(sample59)
print(np.sort(sample59, axis=0)) # 全部都排序
print(np.argsort(sample59, axis=0)) # 給出的是位置
print(sample59[sample59[:, 1].argsort()]) # 按第二列排序
60. How to tell if a given 2D array has null columns? (★★☆)')
如何判斷一個二維數組有全為0的列?
Z= np.random.randint(0,3,(3,20))
print('\n',Z)
print((~Z.any(axis=0)).any())
61. Find the nearest value from a given value in an array (★★☆)')
從數組中找出給定值的最近似值
Z = np.random.uniform(0,1,10)
z = 0.5
m = Z.flat[np.abs(Z - z).argmin()]
print(m)
62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆)')
使用迭代器計算1x3和3x1的數組的和?
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 (★★☆)')
創建一個有名字的數組類 (★★☆)')
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)? (★★★)')
對一個給定數組,如何按第二個數組表示的索引位置將對應的元素+1,注意重復的位置要重復加1?
# Author: Brett Olsen
Z = np.ones(10)
Z1 = np.ones(10)
I=I1 = np.random.randint(0, len(Z), 20)
print(I)
Z += np.bincount(I, minlength=len(Z))
print(Z)
# Another solution
# Author: Bartosz Telenczuk
np.add.at(Z1, I1, 1)
print(Z1)
```python
## 65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★)')
## 如何基于索引列表I,將向量X的各元素累加到數組F上?
```python
#
# Author: Alan G Isaac
X = [1,2,3,4,5,6]
I = [0,0,0,1,1,2] # 比重
F = np.bincount(I,X)
print(F)
66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★★)')
對一個(w,h,3)表示的圖像,如何計算不重復的顏色
w, h = 16,16
I = np.random.randint(0,2,(h,w,3)).astype(np.ubyte)
F = I[...,0]*256*256 + I[...,1]*256 + I[...,2] # 三個顏色
print(F)
n = len((np.unique(F)))
print(np.unique(I))
67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)')
對一個四維數組,如何計算最后兩個軸上的元素和?
A = np.random.randint(0, 10, (3, 4, 5, 6))
print(A.sum(axis=(-2, -1)))
# 方法二
print(A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)) # 把A變為(3,4,-1)把最后兩個軸合并
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? (★★★)')
對一個一維向量D,如何按按權重S來計算算術平均值?
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)
69. How to get the diagonal of a dot product? (★★★)')
獲取點積的對角矩陣?
# Author: Mathieu Blondel
A = np.random.uniform(0,1,(5,5))
B = np.random.uniform(0,1,(5,5))
print()
# 慢
print((np.diag(np.dot(A, B))))
# 快
print(np.sum(A * B.T, axis=1))
# 最快
print(np.einsum("ij,ji->i", A, B))
70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)')
將向量[1,2,3,4,5],元素中間插入3個0,形成新的數組
sample70 = np.array([1,2,3,4,5])
result = np.zeros ((sample70.size-1)*4+1,dtype=np.int)
result[0::4] = sample70
print(result)
71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★)')
將一個5x5x3的數組與5x5的數組相乘?
A = np.random.choice(10, (5, 5, 3))
B = np.random.choice(10, (5, 5))
print(A * B[..., np.newaxis])
72. How to swap two rows of an array? (★★★)')
交換數組的兩行?
# hint 這里還是索引選擇
sample72 = np.random.choice(100,16).reshape(4,-1)
print(sample72)
sample72[[1,2],...]=sample72[[2,1],...]
print(sample72)
73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★)')
使用10個三元數的集合描述10個三角形,找出組成這些三角形邊的集合
# Author: Nicolas P. Rougier
faces = np.random.randint(0, 100, (10, 3))
F = np.roll(faces.repeat(2, axis=1), -1, axis=1) # roll 元素在某一軸方向滾動
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)
74. Given an array C that is a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)')
依據bincount的結果來構造一個數組,使得np.bincount(A)==C?
# bincount 是計算一個整數數組中各元素出現的次數。結果按最大元素的序列來表示。
C = np.array([1, 2, 3, 0, 5])
res = np.array([], dtype=int)
for x in C:
res = np.append(res, np.ones(x) * (x - 1))
print(res.astype(int))
75. How to compute averages using a sliding window over an array? (★★★)')
使用滑動窗口計算數組平均值?
# 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))
76. Consider a one-dimensional array Z, build a two-dimensional array whose first row is (Z[0],Z[1],Z[2]) and each subsequent row is shifted by 1 (last row should be (Z[-3],Z[-2],Z[-1]) (★★★)')
給定一維數組Z,構造一個二維數組,其第一行為Z[0],Z[1],Z[2]),下一行依次偏移1位,最后一行為(Z[-3],Z[-2],Z[-1])
# Author: Joe Kington / Erik Rigtorp
from numpy.lib import stride_tricks
def rolling(a, window):
shape = (a.size - window + 1, window)
strides = (a.itemsize, a.itemsize)
return stride_tricks.as_strided(a, shape=shape, strides=strides)
Z = rolling(np.arange(10), 3)
print(Z)
77. How to negate a boolean, or to change the sign of a float inplace? (★★★)')
改變浮點數的符號?
# 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)
78. Consider 2 sets of points P0,P1 describing lines (2d) and a point p, how to compute distance from p to each line i (P0[i],P1[i])? (★★★)')
用兩個點集來描述的一組線和一個點P,如何計算P點到這些線的距離?
A = np.array([[1, 2], [1, 2], [1, 3], [1, 2]])
B = np.array([[2, 1], [2, 2], [3, 1], [3, 2]])
C = np.array([1.2, 1.2])
print(np.abs(np.cross(A - C, B - C, axis=1)) / np.linalg.norm(A - B, axis=1))
79. Consider 2 sets of points P0,P1 describing lines (2d) and a set of points P, how to compute distance from each point j (P[j]) to each line i (P0[i],P1[i])? (★★★)')
現有由兩個點集P0P1來表示的二維平面的上的線以及一個點集P,計算每個點到每個線的距離? (★★★)')
# Author: Italmassov Kuanysh
def distance(P0, P1, p):
T = P1 - P0
L = (T ** 2).sum(axis=1)
U = -((P0[:, 0] - p[..., 0]) * T[:, 0] + (P0[:, 1] - p[..., 1]) * T[:, 1]) / L
U = U.reshape(len(U), 1)
D = P0 + U * T - p
return np.sqrt((D ** 2).sum(axis=1))
P0 = np.random.uniform(-10, 10, (10, 2))
P1 = np.random.uniform(-10, 10, (10, 2))
p = np.random.uniform(-10, 10, (10, 2))
print(np.array([distance(P0, P1, p_i) for p_i in p]))
80. Consider an arbitrary array, write a function that extract a subpart with a fixed shape and centered on a given element (pad with a fill value when necessary) (★★★)')
對任意的一個數組,編寫一個函數,以一個給定的元素為中心,從數組中抽取一個固定大小的子矩陣(如果需要的話,使用固定的值進行填充)
# Author: Nicolas Rougier
Z = np.random.randint(0,10,(10,10))
shape = (5,5)
fill = 0
position = (1,1)
R = np.ones(shape, dtype=Z.dtype)*fill
P = np.array(list(position)).astype(int)
Rs = np.array(list(R.shape)).astype(int)
Zs = np.array(list(Z.shape)).astype(int)
R_start = np.zeros((len(shape),)).astype(int)
R_stop = np.array(list(shape)).astype(int)
Z_start = (P-Rs//2)
Z_stop = (P+Rs//2)+Rs%2
R_start = (R_start - np.minimum(Z_start,0)).tolist()
Z_start = (np.maximum(Z_start,0)).tolist()
R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()
Z_stop = (np.minimum(Z_stop,Zs)).tolist()
r = [slice(start,stop) for start,stop in zip(R_start,R_stop)]
z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)]
print(r)
R[r] = Z[z]
print(Z)
print(R)
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]]? (★★★)')
對于數組Z=[1,2,3,4,5,6,7,8,9,10,11,12,13,14],如何生成新的數組[[1,2,3,4],[2,3,4,5],[3,4,5,6],[4,5,6,7],...,[11,12,13,14]]?
Z = np.arange(1, 15, dtype=np.uint32)
R = np.lib.stride_tricks.as_strided(Z, (11, 4), (4, 4))
print(R)
# 我的做法,1.16 不支持生成器
for i in np.arange(Z.size - 3):
R = np.vstack([R, Z[i:i + 4]])
# R =np.vstack((Z[i:i + 4] for i in np.arange(Z.size - 3)))
print(R)
82. Compute a matrix rank (★★★)')
計算矩陣的秩
Z = np.random.uniform(0, 1, (1000, 1000))
U, S, V = np.linalg.svd(Z) # Singular Value Decomposition 奇異值分解
# print(U,S,V)
rank = np.sum(S > 1e-10)
print(rank)
83. How to find the most frequent value in an array?★)')
找到矩陣中出現頻率最高
sample83 = np.random.randint(0,5,10)
print(sample83)
print(np.bincount(sample83))
print(np.bincount(sample83).argmax())
84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★)')
從一個10x10矩陣中抽取出所有相鄰的3x3矩陣
sample84 = np.random.randint(0, 10, (5, 5))
Z = sample84
n = 3
# 我的做法
print(sample84)
for i in range(sample84.shape[0] - n + 1):
for j in range(sample84.shape[0] - n + 1):
print(i * 10 + j, sample84[i:i + 3, j:j + 3])
# 答案
print(Z)
i = 1 + (Z.shape[0] - 3)
j = 1 + (Z.shape[1] - 3)
C = np.lib.stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides)
print(C)
85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★)')
構造一個二維數組的子類,使得Z[i,j]=Z[j,i]
class Symtric(np.ndarray):
def __setitem__(self, key, value):
i, j = key
super(Symtric, self).__setitem__((i, j), value)
super(Symtric, self).__setitem__((j, i), value)
def symetric(Z):
return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symtric)
S = symetric(np.random.randint(0, 10, (5, 5)))
S[0, 0] = 42
print(S)
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)) (★★★)')
現有大小為(n,n)的矩陣集合和大小為(n,1)的向量集合,如何計算張量乘法
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)
87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)')
給定一個16x16的矩陣,對其中4x4的塊進行求和?
# Author: Robert Kern
Z = np.random.choice(100,(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)
88. How to implement the Game of Life using numpy arrays? (★★★)')
使用數組實現生命游戲?
#
# 1. 每個細胞的狀態由該細胞及周圍八個細胞上一次的狀態所決定;
# 2. 如果一個細胞周圍有3個細胞為生,則該細胞為生,即該細胞若原先為死,則轉為生,若原先為生,則保持不變;
# 3. 如果一個細胞周圍有2個細胞為生,則該細胞的生死狀態保持不變;
# 4. 在其它情況下,該細胞為死,即該細胞若原先為生,則轉為死,若原先為死,則保持不變
#
# Author: Nicolas Rougier
def iterate(Z):
# Count neighbours
N = (Z[0:-2, 0:-2] + Z[0:-2, 1:-1] + Z[0:-2, 2:] +
Z[1:-1, 0:-2] + Z[1:-1, 2:] +
Z[2:, 0:-2] + Z[2:, 1:-1] + Z[2:, 2:])
# # Apply rules
birth = (N == 3)
survive = ((N == 2) | (N == 3))
Z[...] = 0
Z[1:-1, 1:-1][birth | survive] = 1
return Z
Z = np.random.randint(0, 2, (50, 50))
for i in range(100): Z = iterate(Z)
print(Z)
89. How to get the n largest values of an array (★★★)')
從數組中找出最大的n個值
Z = np.arange(50)
np.random.shuffle(Z) # 將中元素順序隨機化
n = 5
# 慢
print(Z[np.argsort(Z)[-n:]])
# 快
print(Z[np.argpartition(-Z, n)[:n]]) # 最大的5個值是沒有順序的
90. Given an arbitrary number of vectors, build the cartesian product (every combinations of every item) (★★★)')
計算任意向量的笛卡爾積 (★★★)')
# Author: Stefan Van der Walt
def cartesian(arrays):
arrays = [np.asarray(a) for a in arrays]
shape = (len(x) for x in arrays)
ix = np.indices(shape, dtype=int)
ix = ix.reshape(len(arrays), -1).T
for n, arr in enumerate(arrays):
ix[:, n] = arrays[n][ix[:, n]]
return ix
print(cartesian(([1, 2, 3], [4, 5], [6, 7])))
91. How to create a record array from a regular array? (★★★)')
從常規數組創建結構化數組?
Z = np.array([("Hello", 2.5, 3),
("World", 3.6, 2)])
R = np.core.records.fromarrays(Z.T, names='列1,列2,列3', formats='S8,f8,i8')
print(R)
92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★)')
用三種方法計算一個大型數組中每個元素的立方
Z = np.random.choice(100,10000)
print(Z)
print(np.power(Z,3))
print(Z**3)
print(Z*Z*Z)
print(np.einsum('i,i,i->i',Z,Z,Z))
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? (★★★)')
給定一個8X3的數組A和一個2X2的數組B,從A中找出滿足條件的行,條件是B中每一行都有元素出現在A中這一行中?
# Author: Gabe Schwartz
A = np.random.randint(0,5,(8,3))
B = np.array([[1,1],[1,1]])
C = (A[..., np.newaxis, np.newaxis] == B)
rows = np.where(C.any((3,1)).all(1))[0]
print('',A,'\n',B,'\n',rows)
94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★)')
從一個10x3的數組中去除一行元素完全相同的行
# Author: Robert Kern
sample = np.arange(0, 10)
Z = np.random.choice(3, (10, 3))
U = Z[~(np.all(Z[..., 1:] == Z[..., :-1], axis=1))] # 如果某行元素去除第一個元素形成的數組與排除最后一個元素形成的數組相同,則認為這行元素完全相同
print(U)
U = Z[Z.max(axis=-1) != Z.min(axis=-1), :] # 僅限于Z是數值 如果一行元素最大值和最小值相等,則可以判定這行元素是完全相同的
print(U)
95. Convert a vector of ints into a matrix binary representation (★★★)')
把一個8位整型的一維數組表示為二進制的矩陣
I = np.array([0, 1, 2, 4, 8, 16, 32, 64, 128], dtype=np.uint8)
print(np.unpackbits(I[:, np.newaxis], axis=1)) # 將一個8位長整形元素展開成二進制形式
96. Given a two dimensional array, how to extract unique rows? (★★★)')
從二維矩陣中找出不同的行?
Z= np.random.randint(0,2,(6,3))
print(Z)
T = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize*Z.shape[1])))
_,idx = np.unique(T,return_index=True)
print(Z[idx])
uZ = np.unique(Z,axis=0)
print(uZ)
97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★)')
給定數組A,B,使用函數einsum實現求和,矩陣相乘,內積和外積
#使用einsum函數,我們可以使用愛因斯坦求和約定(Einstein summation convention)在NumPy數組上指定操作
A = np.random.uniform(0,1,10) # 均勻分布
B = np.random.uniform(0,1,10) # 均勻分布
np.einsum('i->', A) # 求和
np.einsum('i,i->i', A, B) # 矩陣相乘
np.einsum('i,i', A, B) # 內積
np.einsum('i,j->ij', A, B) # 外積
98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples? (★★★)')
給定用兩組向量(X,Y)描述的一條線,如何進行等距采樣
phi = np.arange(0,10*np.pi,0.1)
a =1
x = a*phi*np.cos(phi)
y = a*phi*np.sin(phi)
dr = (np.diff(x)**2 + np.diff(y)**2)**.5
r = np.zeros_like(x)
r[1:] = np.cumsum(dr)
print(r)
r_int = np.linspace(0, r.max(), 80)
x_int = np.interp(r_int, r, x) #插值
y_int = np.interp(r_int, r, y) #插值
plt.subplot(133)
plt.plot(x,y,x_int,y_int)
99. Given an integer n and a 2D array X, select from X the rows which can be interpreted as draws from a multinomial distribution with n degrees, i.e., the rows which only contain integers and which sum to n. (★★★)')
給定整數n和一個二維數組X,從X中找出滿足條件的行 指數為n的多項式分布
X = np.asarray([[1.0, 0.0, 3.0, 8.0],
[2.0, 0.0, 1.0, 1.0],
[1.5, 2.5, 1.0, 0.0]])
n = 4
print(np.mod(X, 1) == 0)
M = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1)
# np.mod(X,1) 找出整數,
# axis =-1 表示最后一個維度
M = (X.sum(axis=-1) == n)
# 在最后一個維度上和為4
print(X[M])
100. Compute bootstrapped 95% confidence intervals for the mean of a 1D array X (i.e., resample the elements of an array with replacement N times, compute the mean of each sample, and then compute percentiles over the means).
采用自助法計算給定一維數組在95%置信區間上的算術平均值
X = np.random.randn(100) # 一維數組
N = 1000 # 自抽取數量
idx = np.random.randint(0, X.size, (N, X.size)) # 生成1000x100的隨機索引數組
means = np.mean(X[idx], axis=1) # 相當于對每一行的100個抽樣值計算平均值,結果一個大小為1000的一維數組
confint = np.percentile(means, [2.5, 97.5]) # 計算百分位數 百分位數是統計中使用的度量,表示小于這個值的觀察值占總數q的百分比
print(confint)
總結
以上是生活随笔為你收集整理的python创建一个类似于国家象棋棋盘的0-1矩阵_NumPy练习题(全中文并附详细讲解)...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: nat端口限制_Cisco ASA 防火
- 下一篇: python特征选择relieff图像特