如何根据每个记录及其以前的记录筛选NumPy数组

2024-10-04 11:35:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在考虑将我的代码转换为与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),以便删除输出列表中会影响输入列表的记录。我在网上看了一些例子,但我仍然停留在如何做到这一点上


Tags: 函数代码功能numpyclean列表valuedef
1条回答
网友
1楼 · 发布于 2024-10-04 11:35:19

一种非常标准的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')])

相关问题 更多 >