python - 查找两个值之间的唯一数据

标签 python numpy

我希望快速找到两个值之间的唯一值(在本例中为纪元时间)的索引,仅返回 minVal、maxVal 之间的所有值(但不是两次)简化的示例如下:

import numpy as np 
minVal = 198000  
maxVal = 230000
uniqueExample = np.arange(300, dtype=float) # this is how it expected to exist
# this is how it actually exists, a small repeated values randomly interspersed  
example = np.insert(uniqueExample, 200, np.arange(200,210.))*1000 # *1000 to differentiate from the indices


# now begin process of isolating 
mask = (example < maxVal) & (example > minVal)
idx = np.argwhere(mask).squeeze() 

这将返回不期望的结果

array([199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211,
   212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224,
   225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237,
   238, 239])

为了改进结果,添加了以下内容

 # this was 
if len(set(example[idx])) != len(example[idx]):
    dupes = np.array([x for n, x in enumerate(example[idx]) if x in example[idx][:n]]).squeeze()
    idx = np.delete(idx, np.nonzero(np.in1d(example[idx], dupes).squeeze()[::2]))   

这将返回所需的结果

array([199, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221,
   222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234,
   235, 236, 237, 238, 239])

这在检索索引 O(100) 时工作​​正常,但对于较大的数据集 O(100,000)+ 来说这很慢(有时似乎没有删除所有重复项),所以我想出了一些选项似乎仍然很慢,我希望有人可以解释这些慢的原因或找到更好/更快的方法来做到这一点。速度是一个问题。

import time
# define testing function for test functions below 
def timing(f, n, a):
    print(f.__name__,)
    r = range(n)
    t1 = time.perf_counter()
    for i in r:
        f(a[0],a[1],a[2]); f(a[0],a[1],a[2]); 
    t2 = time.perf_counter()
    print(round(t2-t1, 3))

def gettimeBase(example, minVal, maxVal):
    # this is target (speed and simplicity), but returns duplicates
    mask = (example >= minVal) & (example  < maxVal)
    idx = np.argwhere(mask).squeeze()
    return idx
## now one's that don't return duplicates
def gettime1(example, minVal, maxVal):
    mask = (example >= minVal) & (example < maxVal)
    idx = np.argwhere(mask).squeeze()
    if np.size(idx) == 0:
        idx = None
    if len(set(example[idx])) !=len(example[idx]):
     ## when there are duplicate times on the server
        times, idxUnique = np.unique(example, return_index=True)
        mask2 = (times >= minVal) & (times < maxVal)
        idx2 = np.argwhere(mask2).squeeze()
        idx = idxUnique[idx2].squeeze()
        assert (sorted(set(example[idx])) == example[idx]).all(), 'Data Still have duplicate times'
     return idx

def gettime2(example, minVal, maxVal):
    if len(set(example)) != len(example):
        ## when there are duplicate times on the server
        times, idxUnique = np.unique(example, return_index=True)
        mask2 = (times >= minVal) & (times < maxVal)
        idx2 = np.argwhere(mask2).squeeze()
        idx = idxUnique[idx2].squeeze()
    else:
        mask = (example >= minVal) & (example < maxVal)
        idx = np.argwhere(mask).squeeze()
    if np.size(idx) == 0:
        return None
    assert (sorted(set(example[idx])) == example[idx]).all(), 'Data Still have duplicate times'
    return idx

testdata = (example, minValue, maxValue)
testfuncs = gettimeBase, gettime1, gettime2
for f in testfuncs:
    timing(f, 100, testdata)

测试结果为(python 3):

获取时间基准 0.127

获取时间1 35.103

获取时间2 74.953

最佳答案

选项 1

numpy.unique

此选项速度很快,但它将返回每个重复项的第一个出现的索引,而在您的问题中,您似乎正在获取一个最后的索引复制。这意味着此方法返回的索引将与您所需的输出不匹配,但它们对应的值将是相同的。

vals, indices = np.unique(example[mask], return_index=True)
indices + np.argmax(mask)

array([199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 220, 221,
       222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234,
       235, 236, 237, 238, 239], dtype=int64)

这是我提到的警告:

desired = np.array([199, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221,
   222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234,
   235, 236, 237, 238, 239])

np.array_equal(start + idx, desired)
# False

np.array_equal(example[start + idx], example[desired])
# True

选项 2

numpy.unique + numpy.flip

f = np.flip(example[mask])
vals, indices = np.unique(f, return_index=True)
final = f.shape[0] - 1 - indices
final + np.argmax(mask)

array([199, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221,
       222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234,
       235, 236, 237, 238, 239], dtype=int64)

这实际上捕获了最后一次出现,但增加了更多开销:

np.array_equal(final + idx[0], desired)
# True

性能(我包括了一些设置成本)

def chris1(arr, mn, mx):
    mask = (arr < mx) & (arr > mn)
    vals, indices = np.unique(arr[mask], return_index=True)
    return indices + np.argmax(mask)

def chris2(arr, mn, mx):
    mask = (arr < mx) & (arr > mn)
    f = np.flip(arr[mask])
    vals, indices = np.unique(f, return_index=True)
    final = f.shape[0] - 1 - indices
    return final + np.argmax(mask)

def sbfrf(arr, mn, mx):
    mask = (arr < mx) & (arr > mn)
    idx = np.argwhere(mask).squeeze()
    if len(set(example[idx])) != len(example[idx]):
        dupes = np.array([x for n, x in enumerate(example[idx]) if x in example[idx][:n]]).squeeze()
    idx = np.delete(idx, np.nonzero(np.in1d(example[idx], dupes).squeeze()[::2]))
    return idx

In [225]: %timeit chris1(example, 198_000, 230_000)
29.6 µs ± 133 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [226]: %timeit chris2(example, 198_000, 230_000)
36.5 µs ± 98.6 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [227]: %timeit sbfrf(example, 198_000, 230_000)
463 µs ± 7.77 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

关于python - 查找两个值之间的唯一数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53382357/

相关文章:

python - 将计算方法传递给函数的最简单方法

python - 用另一个数据框中的匹配 ID 替换 Pandas 中的单元格值

python - 使用 Numpy 过滤两个数据帧

python - Cython:转置内存 View

Python - 克隆列表

python - pandas shift 不适用于列和行的子集

python - 错误: The truth value of an array with more than one element is ambiguous

python - 重新分配一个巨大的列表/数组会导致内存泄漏吗?

python - 在 Django 1.5 中将电子邮件设置为用户名

python - 属性错误: 'Corn' object has no attribute '_Plant__symbol'