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

How to efficiently check conditions on two columns and perform operation on third column in 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
   



  

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

你可以为此使用面具:

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

中输出

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

如果你想像你的代码那样结合一些条件。您可以使用运算符 & 表示 | 表示 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

如果您想就地修改第 2 列,如

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

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