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

2024-09-24 22:32:46 发布

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

我有一些非常大的数据集的问题。我需要找到一种可靠而快速的方法来查找/替换结构化数组中的条目。我正在寻找一个解决方案,没有循环的所有条目。我知道有C语言的快速解决方案,但我不知道如何在python中实现这一点。我也很想知道是否有一个numpy函数就是为了这个目的!你知道吗

我正在使用python2.7.13和numpy1.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个对象的数据子样本here!它的结构由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

Tags: the数据posdatanpposition条目where
1条回答
网友
1楼 · 发布于 2024-09-24 22:32:46

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

相关问题 更多 >