Numpy怎么使用最高效,5个技巧送给你!
马哥Linux运维
共 5050字,需浏览 11分钟
·
2021-04-17 22:25
本文作者将分享 5 个优雅的 Python Numpy 函数,有助于高效、简洁的数据处理。
a = np.array([[1, 2, 3, 4],
[5, 6, 7, 8]])
a.shape
(2, 4)
a.reshape(1,-1)
array([[1, 2, 3, 4, 5, 6, 7, 8]])
a.reshape(-1,1)
array([[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8]])
a.reshape(-1,4)
array([[1, 2, 3, 4],
[5, 6, 7, 8]])a.reshape(-1,2)
array([[1, 2],
[3, 4],
[5, 6],
[7, 8]])a.reshape(2,-1)
array([[1, 2, 3, 4],
[5, 6, 7, 8]])a.reshape(4,-1)
array([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
a.reshape(2,2,-1)
array([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])a.reshape(2,-1,1)
array([[[1],
[2],
[3],
[4]],
[[5],
[6],
[7],
[8]]])
a.reshape(-1,-1)
ValueError: can only specify one unknown dimensiona.reshape(3,-1)
ValueError: cannot reshape array of size 8 into shape (3,newaxis)
array = np.array([10, 7, 4, 3, 2, 2, 5, 9, 0, 4, 6, 0])index = np.argpartition*(array, -5)[-5:]
index
array([ 6, 1, 10, 7, 0], dtype=int64)np.sort(array[index])
array([ 5, 6, 7, 9, 10])
#Example-1
array = np.array([10, 7, 4, 3, 2, 2, 5, 9, 0, 4, 6, 0])
print (np.clip(array,2,6))[6 6 4 3 2 2 5 6 2 4 6 2]#Example-2
array = np.array([10, -1, 4, -3, 2, 2, 5, 9, 0, 4, 6, 0])
print (np.clip(array,2,5))[5 2 4 2 2 2 5 5 2 4 5 2]
arr = np.arange(10)
arrarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])# Define the codition, here we take MOD 3 if zero
condition = np.mod(arr, 3)==0
conditionarray([ True, False, False, True, False, False, True, False, False,True])np.extract(condition, arr)
array([0, 3, 6, 9])
np.extract(((arr > 2) & (arr < 8)), arr)array([3, 4, 5, 6, 7])
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
b = np.array([3,4,7,6,7,8,11,12,14])
c = np.setdiff1d(a,b)
carray([1, 2, 5, 9])
选自TowardsDataScience,作者:Baijayanta Roy
机器之心编译
文章转载:菜鸟学Python
(版权归原作者所有,侵删)
评论