如何用NaN替换数组的空值

2024-04-24 04:27:23 发布

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

我想创建一个形状为:(N,3)的数组。但是,如果不可能,我想用NaN替换缺少的值

这是我的密码:

from scipy import spatial
import numpy as np
vertices = numpy.array([[ 0.82667452,  0.89591247,  0.91638623],
                        [ 0.10045271,  0.50575086,  0.73920507],
                        [ 0.06341482,  0.17413744,  0.6316301 ],
                        [ 0.75613029,  0.82585983,  0.10012549],
                        [ 0.45498342,  0.5636221 ,  0.10940527],
                        [ 0.46079863,  0.54088544,  0.1519899 ],
                        [ 0.61961934,  0.78550213,  0.43406491],
                        [ 0.12654252,  0.7514213 ,  0.18265301],
                        [ 0.94441365,  0.00428673,  0.46893573],
                        [ 0.79083297,  0.70198129,  0.75670947]])
tree = spatial.cKDTree(vertices)
iof = tree.query_ball_point(vertices,0.3,n_jobs=-1,return_sorted=False)
faces_eampty = np.empty((len(vertices),3))
faces_eampty[:] = np.NaN
faces = np.array([l[0:3] for l in iof])
faces_eampty[:faces.shape[0], :faces.shape[1]] = faces
np.savetxt("normaltest_2.txt",faces,fmt='%s')

我希望结果是这样的:

faces: [[0 6 9]
 [1 2 4]
 [1 2 NaN]
 [3 4 5]
 [1 NaN NaN]
 [1 2 3]
 [0 1 3]
 [1 2 NaN]
 [5 NaN NaN]
 [0 1 3]]

我该怎么做


Tags: importnumpytree密码np数组nanarray
1条回答
网友
1楼 · 发布于 2024-04-24 04:27:23

考虑到每个点的查询结果可能有1个、2个或更多,最好不要使用数组,直到所有值都具有相同的形状(numpy数组需要)

from scipy import spatial
import numpy as np
vertices = np.array([[ 0.82667452,  0.89591247,  0.91638623],
                        [ 0.10045271,  0.50575086,  0.73920507],
                        [ 0.06341482,  0.17413744,  0.6316301 ],
                        [ 0.75613029,  0.82585983,  0.10012549],
                        [ 0.45498342,  0.5636221 ,  0.10940527],
                        [ 0.46079863,  0.54088544,  0.1519899 ],
                        [ 0.61961934,  0.78550213,  0.43406491],
                        [ 0.12654252,  0.7514213 ,  0.18265301],
                        [ 0.94441365,  0.00428673,  0.46893573],
                        [ 0.79083297,  0.70198129,  0.75670947]])
tree = spatial.cKDTree(vertices)
iof = tree.query_ball_point(vertices,0.3,n_jobs=-1,return_sorted=False)
faces = [l[0:3] for l in iof]

# append a NaN value if there are less than n values
# where n are the most results from the query from 1 point
_max = max([len(f) for f in faces])

for f in faces:
    if len(f) < _max:
        f.append(np.NaN)

np.array(faces)
>>> array([[ 0.,  9.],
           [ 1., nan],
           [ 2., nan],
           [ 3., nan],
           [ 4.,  5.],
           [ 4.,  5.],
           [ 6., nan],
           [ 7., nan],
           [ 8., nan],
           [ 0.,  9.]])

相关问题 更多 >