【问题标题】:flexible query based on two numpy arrays基于两个numpy数组的灵活查询
【发布时间】:2016-10-31 18:27:38
【问题描述】:

我想创建一个基于 numpy 数组的动态查询。理想情况下,根据第二个数组 (cond) 中每一列的条件,应该返回一个数组 (uu) 的索引。

下面的示例演示了我的想法,它使用循环工作。我想知道是否有更有效的方法。感谢您的帮助。

import numpy as np
# create an array that has four columns, each contain a vector (here: identical vectors)
n = 101
u = np.linspace(0,100,n)
uu = np.ones((4, n)) * u
# ideally I would like the indices of uu 
#     (so I could access another array of the same shape as uu)
#     that meets the following conditions: 
#       the condition based on which values in uu should be selected
#          in the first column (index 0) all values <= 10. should be selected
#          in the second column (index 1) all values <= 20. should be selected
cond = np.array([10,20])


# this gives the correct indices, but in a series of 1D solutions
#     this would work as a work-around
for i in range(cond.size):
    ix = np.where(uu[i,:] <= cond[i])
    print(ix)


# this seems like a work-around using True/False
# but here I am not sure how to best convert this to indices
for i in range(cond.size):
    uu[i,:] = uu[i,:] <= cond[i]
print(uu)

【问题讨论】:

  • uu[i,:] 选择行而不是列,对吗?不确定我的问题是否正确。
  • cond 不应该总是有和 uu 一样多的列吗?

标签: python arrays numpy filtering


【解决方案1】:

Numpy 允许直接比较数组:

import numpy as np
# just making my own uu with random numbers
n = 101
uu = np.random.rand(n,4)

# then if you have an array or a list of values...
cond = [.2,.5,.7,.8]

# ... you can directly compare the array to it
comparison = uu <= cond

# comparison now has True/False values, and the shape of uu
# you can directly use comparison to get the desired values in uu 
uu[comparison] # gives the values of uu where comparison ir True

# but if you really need the indices you can do
np.where(comparison) 
#returns 2 arrays containing i-indices and j-indices where comparison is True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    相关资源
    最近更新 更多