gpt4 book ai didi

python - 在python中将 "nan"移到数组的开头

转载 作者:行者123 更新时间:2023-12-03 14:31:47 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Python: Justifying NumPy array

(2 个回答)


去年关闭。




如果我有一个带有 nan 的数组,它看起来像这样:

array([[ 0.,  0.,  0.,  0.],
[ 0., 0., nan, nan],
[ 0., 1., 3., nan],
[ 0., 2., 4., 7.],
[ 0., nan, 2., nan],
[ 0., 4., nan, nan]])
如何在不改变形状的情况下将所有 nan 移动到数组的开头?
像这样的事情:
array([[ 0.,  0.,  0.,  0.],
[ nan, nan, 0., 0.],
[ nan, 0., 1., 3.],
[ 0., 2., 4., 7.],
[ nan, nan, 0., 2.],
[ nan, nan, 0., 4.]])

最佳答案

这是一种方法:

# find the position of nan itms in "a"
In [19]: mask = np.isnan(a)
# put them at the beginning by sorting the mask in a descending order
In [20]: nan_pos = np.sort(mask)[:,::-1]
# the new position of non_non items is the inverse of non-mask sorted ascending
In [21]: not_nan_pos = np.sort(~mask)

In [22]: emp = np.empty(a.shape)

In [23]: emp[nan_pos] = np.nan

In [24]: emp[not_nan_pos] = a[~mask]

In [25]: emp
Out[25]:
array([[ 0., 0., 0., 0.],
[nan, nan, 0., 0.],
[nan, 0., 1., 3.],
[ 0., 2., 4., 7.],
[nan, nan, 0., 2.],
[nan, nan, 0., 4.]])

关于python - 在python中将 "nan"移到数组的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63031346/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com