PYTHON:检查和编辑结构化数组中的元素(如果存在)的最快方法是什么?



我对非常大的数据集有一些问题。我需要找到一种可靠且快速的方法来查找/替换结构化数组中的条目。我正在寻找一种不循环所有条目的解决方案。我知道有针对 C 的快速解决方案,但我不知道如何在 python 中解决这个问题。我也想知道是否有用于此目的的 numpy 功能!

我正在使用 Python 2.7.13 和 numpy 1.12.1!

任务:通过在data_centrals的中心列表中找到data_orphan中孤儿的光晕,将孤儿的所有位置设置为data_centrals的位置。

import numpy as np
data =  Structured array:
class:  ndarray
shape:  (189258912,)
dt = [('hostid', '<u8'), ('z_pos', '<f8'), ('x_pos', '<f8'),
('y_pos', '<f8'), ('haloid', '<u8'), ('orphan', 'i1')]

已编辑:可以在此处下载包含 200 个对象的数据子样本!它的结构由dt给出:第一列 ->hostid,第二列 ->z_pos,依此类推。它可以复制/粘贴到python外壳或脚本中...

您可以在下面找到设置位置的代码。

问题:是否有聪明的方法来搜索光环并设置位置而无需循环访问data_orphan的所有条目?

data_centrals=data[np.where(data['haloid']==data['hostid'])] # (111958237,)
data_orphans=data[np.where(data['orphan']==2)]               # (61870681,)
a=0
while a<len(data_orphans):
#check where in data_centrals the haloid of the orphan can be found
position=np.where(data_centrals['haloid']==data_orphans['haloid'][a])
#find the position of data_orphan['haloid'][a] in data
position_data=np.where(data['hostid']==data_orphans['hostid'][a])
#set the positions
data['x_pos'][int(position_data[0])]=data_centrals['x_pos'][int(position[0])]        
data['y_pos'][int(position_data[0])]=data_centrals['y_pos'][int(position[0])]       
data['z_pos'][int(position_data[0])]=data_centrals['z_pos'][int(position[0])]
a+=1

如果你的数据结构是一个普通的、无序列表或数组,那么答案是否定的。找到特定元素需要线性时间 O(n)。如果列表/数组是有序的,您可以在 O(lg n) 时间内进行二叉搜索。您也可以考虑使用具有更好搜索时间的平衡 BST 或 python 字典等替代数据结构,但这种方法是否合适,这取决于数据的结构。

相关内容

最新更新