Numpy怎么使用最高效,5個技巧送給你!

選自TowardsDataScience,作者:Baijayanta Roy
機器之心編譯
本文作者將分享 5 個優(yōu)雅的 Python Numpy 函數(shù),有助于高效、簡潔的數(shù)據(jù)處理。

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])
推薦閱讀:
入門: 最全的零基礎(chǔ)學(xué)Python的問題 | 零基礎(chǔ)學(xué)了8個月的Python | 實戰(zhàn)項目 |學(xué)Python就是這條捷徑
干貨:爬取豆瓣短評,電影《后來的我們》 | 38年NBA最佳球員分析 | 從萬眾期待到口碑撲街!唐探3令人失望 | 笑看新倚天屠龍記 | 燈謎答題王 |用Python做個海量小姐姐素描圖 |
趣味:彈球游戲 | 九宮格 | 漂亮的花 | 兩百行Python《天天酷跑》游戲!
AI: 會做詩的機器人 | 給圖片上色 | 預(yù)測收入 | 碟中諜這么火,我用機器學(xué)習(xí)做個迷你推薦系統(tǒng)電影
年度爆款文案
點閱讀原文,領(lǐng)廖雪峰數(shù)據(jù)分析資料!
評論
圖片
表情


