python - 如何根据每条记录及其上一条记录过滤 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 中),以便我可以删除输出列表中会影响输入列表的记录。我在网上查看了示例,但我仍然坚持如何做到这一点。
解决方案
一个非常标准的 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')])
推荐阅读
- python - 如何比较熊猫中的两列值
- python - 在特定的excel单元格中带有xlsxwrite的np.array
- excel - 导入或上传excel文件时Laravel Excel上的ErrorException未定义数组键7
- android - AIDL 文件中无法识别注释(“@”意外)
- python - Django:从相关模型中查询数据
- kubernetes - K8S groundnuty/k8s-wait-for 映像无法作为 init 容器启动(带 helm)
- vue.js - Buefy 表未在渲染函数中传递道具
- gradle - 配置项目 ':app' 时出现问题。从服务器收到状态码 403:Forbidden dl.bintray.com
- java - 如何检查ArrayList中是否已经存在字符串?
- python - 如何在 Python 中获取 Github 存储库的最新活动?