如何在python中高效地检查两列的条件并对第三列执行操作



我有三列,其中有数千行。第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



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])

您可以为此使用掩码:

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中的输出

如果您想组合一些条件,比如您的代码。在np.where:中,可以对使用运算符&,对<em]或>则使用|

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

如果你想修改第二列,就像芭蕾舞演员回答一样

my_data[:, 2][indices] = my_data[:, 2][indices] / some_value

np.logical_andnp.logical_or也是能够处理这些条件的其它模块;如果条件超过两个,则这些模块必须用作np.logical_and.reducenp.logical_or.reduce

也许使用panda更适合此任务,您可以定义条件并将其应用于表格数据,而无需任何显式循环。

最新更新