numpy必知必会-第二天

6 替换array中的元素,并赋值给新的array

例如:
输入arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
输出out为array([ 0, -1, 2, -1, 4, -1, 6, -1, 8, -1])
arr为array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
out = np.where(arr  % 2 == 1 , -1 ,  arr)
print(out)
print(arr)

输出:

[ 0 -1  2 -1  4 -1  6 -1  8 -1]
[0 1 2 3 4 5 6 7 8 9]

7 如何改变array的形状

例如:
输入arr=np.arange(10)
输出array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])

arr=np.arange(10)
arr.reshape(2, -1)

输出

array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])

8 如何垂直堆叠两个array

例如:
输入a = np.arange(10).reshape(2,-1),b = np.repeat(1, 10).reshape(2,-1)
输出> array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]])
a = np.arange(10).reshape(2,-1)
b = np.repeat(1, 10).reshape(2,-1)
np.concatenate([a, b], axis=0)

输出

array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1]])

你也可以通过以下操作实现。但上面的方式更通用。

np.vstack([a, b])
np.r_[a, b]

9 如何水平堆叠两个array

例如:
输入a = np.arange(10).reshape(2,-1),b = np.repeat(1, 10).reshape(2,-1)
输出
array([[0, 1, 2, 3, 4, 1, 1, 1, 1, 1],
[5, 6, 7, 8, 9, 1, 1, 1, 1, 1]])
a = np.arange(10).reshape(2,-1)
b = np.repeat(1, 10).reshape(2,-1)
np.concatenate([a, b], axis=1)

10 如何通过numpy的内建函数实现如下操作

输入a = np.array([1,2,3])
输出array([1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3])

a = np.array([1,2,3])
np.repeat(a, 3), np.tile(a, 3)

输出

(array([1, 1, 1, 2, 2, 2, 3, 3, 3]), array([1, 2, 3, 1, 2, 3, 1, 2, 3]))

现在你知道了repeat和tile的区别,接下来就可以进行如下操作完成任务了

np.r_[np.repeat(a, 3), np.tile(a, 3)]

输出

array([1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3])

 

posted @ 2020-12-04 17:13  Tracydzf  阅读(140)  评论(0编辑  收藏  举报