【问题标题】:Python - Select row in NumPy array where multiple conditions are metPython - 在 NumPy 数组中选择满足多个条件的行
【发布时间】:2017-01-27 15:55:43
【问题描述】:

我的程序包含许多不同的 NumPy 数组,每个数组中都有各种数据。数组的一个例子是:

x = [5, 'ADC01', Input1, 25000], # Where [TypeID, Type, Input, Counts]
    [5, 'ADC01', Input2, 40000]

我可以从单独的数组中检索TypeInput 的值。那我要说

Counts = x[0,3] where Type = 'ADC01' and Input = 'Input2'

显然不会这样写。在我只需要满足一个条件的情况下,我使用过:

InstType_ID = int(InstInv_Data[InstInv_Data[:,glo.inv_InstanceName] == Instrument_Type_L][0,glo.inv_TypeID])

在这里,它在数组 (InstInv_Data) 中的“InstanceName”列中查找并找到与 Instrument_Type 的匹配项。然后它将“TypeID”列分配给 InstType_ID。我基本上想添加一个and 语句,以便它还在另一列中查找另一条匹配的数据。

编辑:我只是认为我可以尝试分两个单独的步骤执行此操作。返回InputCounts 列,其中Type-Column = Type。但是,我不确定如何实际返回两列,而不是特定的一列。像这样的:

Intermediate_Counts = (InstDef_Data[InstDef_Data[:,glo.i_Type] == Instrument_Type_L][0,(glo.i_Input, glo.i_Counts])

【问题讨论】:

    标签: python arrays python-2.7 numpy


    【解决方案1】:

    您可以使用a & b 对两个布尔数组ab 执行逐元素与运算:

    selected_rows = x[(x[:,1] == 'ADC01') & (x[:,2] == 'Input2')]
    

    同样,使用 a | b 表示 OR,使用 ~a 表示 NOT。

    【讨论】:

    • 谢谢,我试图做类似的事情,但我对放置括号的位置感到困惑。效果很好!
    猜你喜欢
    • 2019-02-10
    • 2014-07-17
    • 1970-01-01
    • 2021-08-08
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多