簡體   English   中英

在數組中查找值並有效地更改它們

[英]Find values in array and change them efficiently

我正在處理大約30萬個值的大型數組。 它具有10萬行和3列。 我正在使用此數組進行迭代,如果第一列中的任何值超過了可以說10的限制,我希望替換該數字。 有沒有比運行類似這樣更有效的方法?:

for i in range(N):
    if array[i][0]>10:
        array[i][0] = 0 

我還需要對其他兩列重復此順序,所有其他迭代中都包含該順序,這會使我的代碼運行緩慢。

將您的數組轉換為numpy數組( numpy.asarray ),然后使用以下內容替換值:

import numpy as np
N = np.asarray(N)

N[N > 10] = 0

numpy.asarray文檔

我假設您可能不想為每列使用相同的閾值/替換值。 在這種情況下,您可以將三個項目打包在一個元組列表中並進行遍歷。

import numpy as np

arr = np.ndarray(your_array)
#Edited with your values, and a more than symbol
threshold = 10
column_id = 0
replace_value = 0
arr[arr[:, column_id] > threshold, column_id] = replace_value

根據需要設置thresholdcolumn_idreplace_value

如果我對您的理解正確,那么您正在尋找類似的東西:

>>> from numpy import array
>>> a = array([[1,2,3],[4,5,6],[7,8,9]])
>>> a
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> a[a>5]=10       # <--- here the "magic" happens
>>> a
array([[ 1,  2,  3],
       [ 4,  5, 10],
       [10, 10, 10]])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM