我有三列數千行。第 1 列和第 2 列中的數字從 1 變為 6。我希望檢查第 1 列和第 2 列中的數字組合,以將第 3 列中的值除以某個值。
1 2 3.036010
1 3 2.622544
3 1 2.622544
1 2 3.036010
2 1 3.036010
此外,如果交換第 1 列和第 2 列的值,則第 3 列將除以相同的數字。例如,對于 1 2 和 2 1 組合,第 3 列可以除以相同的值。我目前的方法可以完成這項作業,但我必須手動撰寫幾個條件。執行此任務的更有效方法是什么?提前致謝!
my_data = np.loadtxt('abc.dat')
for row in my_data:
if row[0] == 1 and row[1] == 2:
row[3]/some_value
uj5u.com熱心網友回復:
您可以為此使用掩碼:
import numpy as np
my_data = np.column_stack([np.random.randint(1, 6, (1000, 2)), np.random.randn(1000)])
some_value = 123
mask = my_data[:, 0] == my_data[:, 1]
# divide
my_data[mask, 2] /= some_value
輸出在my_data
uj5u.com熱心網友回復:
也許使用pandas更適合此任務,您可以定義條件并將它們應用于表格資料,而無需任何顯式回圈。
uj5u.com熱心網友回復:
Numpy 提供np.where了允許矢量化測驗的功能:
result = np.where(data[:, 0] == data[:, 1], data[:, 2]/some_value, data[:, 2])
或者,如果您想就地更改陣列:
data[:, 2] = np.where(data[:, 0] == data[:, 1], data[:, 2]/some_value, data[:, 2])
uj5u.com熱心網友回復:
如果你想結合一些條件,比如你的代碼。您可以使用運算子&for and or |for or in np.where:
cond1 = my_data[:, 0] == 1 # cond is a masked Boolean array for where the first condition is satisfied
cond2 = my_data[:, 1] == 2
some_value = 10
indices = np.where(cond1 & cond2)[0] # it gets indices for where the two conditions are satisfied
# indices = np.where(cond1 | cond2)[0] # it gets indices for where at least one of the masks is satisfied
result = my_data[:, 2][indices] / some_value # operation is done on the specified indices
如果你想修改第二列,就像Ballesta 回答的那樣
my_data[:, 2][indices] = my_data[:, 2][indices] / some_value
np.logical_and以及np.logical_or是否也可以處理這些情況的其他模塊;如果條件多于兩個np.logical_and.reduce,則必須使用這些模塊。np.logical_or.reduce
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/449874.html
上一篇:Numba:索引向量會出錯
