![](/img/trans.png)
[英]What is the proper way of checking if element exists and is true in a python dictionary?
[英]PYTHON: What is the fastest way of checking and editing an element in a structured array if it exists?
我有非常大的数据集的一些问题。 我需要找到一种可靠且快速的方法来查找/替换结构化数组中的条目。 我在寻找一种不循环所有条目的解决方案。 我知道有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 shell或脚本中。
您可以在下面找到设置位置的代码。
问题: 有没有一种聪明的方法可以搜索卤素并设置位置而不循环遍历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字典,以缩短搜索时间,但是如果合适的话,则取决于数据的结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.