![](/img/trans.png)
[英]Remove row from a numpy array according to some condition and concatenate result
[英]Python Remove Column from Numpy Array based on some Condition
標題說明了一切。
假設我有一個numpy數組,其中包含的值總計為1。
[0.5 0.3 0.1 0.05 0.03 0.01]
我想刪除小於0.05的所有數組值,同時刪除相應的列,這將導致這樣的數組:
[0.5 0.3 0.1 0.05]
當然有實現此目的的方法。 但是我對到目前為止產生的代碼不滿意。 我覺得必須有一種優雅的方法來使用Python實現這一目標。
謝謝你的幫助
編輯:
謝謝您的幫助。 我覺得自己已經走對了。 我只是還不知道如何使用語法。 但是,不了解不贊成票。 :(
a = [0.5 0.3 0.1 0.05 0.03 0.01]
print a[a >= .05]
聽起來您有一個2D數組(從短語“同時刪除相應的列 ”判斷)。
如果創建一個布爾數組idx
對於要保留的idx
True,則可以使用arr[:, idx]
僅選擇那些列:
import numpy as np
np.set_printoptions(formatter={'float': '{:0.2f}'.format})
np.random.seed(1)
arr = np.random.random((3,4))
mask = (arr < 0.05)
idx = mask.any(axis=0)
result = arr[:, ~idx]
print(arr)
# [[0.42 0.72 0.00 0.30]
# [0.15 0.09 0.19 0.35]
# [0.40 0.54 0.42 0.69]]
print(result)
# [[0.42 0.72 0.30]
# [0.15 0.09 0.35]
# [0.40 0.54 0.69]]
numpy.delete
是你的朋友
import numpy as np
a = np.array([0.5 , 0.3 , 0.1 , 0.05, 0.03, 0.01])
a = np.delete(a,np.where(a < 0.05))
np.delete(a, 1)
將創建的副本a
,然后刪除a[1]
從復制。 a
仍然未受影響。 要強制在改變a
,做我們做a = np.delete(a,np.where(a < 0.05))
np.delete
適用於高維數組。 對於高維數據,您必須做更多的工作來選擇正確的np.where
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.