首页 > 解决方案 > 如何根据每条记录及其上一条记录过滤 NumPy 数组

问题描述

我正在考虑将我的代码转换为与 NumPy 一起使用,并且我具有以下功能:

def Clean_One_State(ListsToConvert):
    # Removes duplicate states
    prev_bool = 2
    returnlist = []
    for value in enumerate(ListsToConvert[1:], 0):
        if value[1] != prev_bool:
            try:
                returnlist.append(value)
                prev_bool = value[1]
            except IndexError:
                returnlist.append(value)
                prev_bool = value[1]
    return returnlist

在一个句子中,该函数删除输入中与前一个记录具有相同状态的记录。对于您自己的需要,函数的输入和输出是:

In:[['Event Time', 'State at A'],[0.0, 1], [0.03253, 1], [0.04757, 0], 
    [0.08479, 0], [0.98534, 1], [0.98748, 1], [1.03602, 0], [1.03717, 0],
    [1.95898, 0], [1.96456, 1], [2.00913, 1], [2.01547, 0]...
Out: [[0.0, 1], [0.04757, 0], [0.98534, 1], [1.03602, 0], [1.96456, 1], [2.01547, 0]...

理想情况下,我希望能够查看输入列表(在 NumPy 中),以便我可以删除输出列表中会影响输入列表的记录。我在网上查看了示例,但我仍然坚持如何做到这一点。

标签: pythonnumpy

解决方案


一个非常标准的 numpy 方法是使用高级索引:

data = [['Event Time', 'State at A'],[0.0, 1], [0.03253, 1], [0.04757, 0], 
        [0.08479, 0], [0.98534, 1], [0.98748, 1], [1.03602, 0], [1.03717, 0],
        [1.95898, 0], [1.96456, 1], [2.00913, 1], [2.01547, 0]]

# convert to array
ar = np.array([*map(tuple,data[1:])],dtype=[*zip(data[0],(float,int))])
ar
# array([(0.     , 1), (0.03253, 1), (0.04757, 0), (0.08479, 0),
#        (0.98534, 1), (0.98748, 1), (1.03602, 0), (1.03717, 0),
#        (1.95898, 0), (1.96456, 1), (2.00913, 1), (2.01547, 0)],
#       dtype=[('Event Time', '<f8'), ('State at A', '<i8')])

# find places where State at A changes and select them from ar
# prepend something that is not equal to the first State at A, so the 
# very first item is also selected
ar[np.diff(ar['State at A'],prepend=ar['State at A'][0]-1).nonzero()]
# array([(0.     , 1), (0.04757, 0), (0.98534, 1), (1.03602, 0),
#        (1.96456, 1), (2.01547, 0)],
#       dtype=[('Event Time', '<f8'), ('State at A', '<i8')])

推荐阅读