如何在numpy 2D数组中插入NaN数组

2024-06-16 14:53:43 发布

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

我试图在2D数组的特定位置插入任意数量的NaN值行。我将微控制器的一些数据记录在一个.csv文件中,并用python进行解析。在

数据存储在一个3列的2D数组中,如下所示

[(122.0, 1.0, -47.0) (123.0, 1.0, -47.0) (125.0, 1.0, -44.0) ..., 
(39.0, 1.0, -47.0) (40.0, 1.0, -45.0) (41.0, 1.0, -47.0)]

第一列是序列计数器。我要做的是遍历序列值diff current和previous sequence number,插入尽可能多的缺少序列的nan行。在

基本上

^{pr2}$

会变成

[(122.0, 1.0, -47.0) (123.0, 1.0, -47.0) (nan, nan, nan) (125.0, 1.0, -44.0)]

但是np.insert的以下实现会产生一个错误

while (i < len(list[1])):
     pid = list[i][0]
     newMissing = (pid - LastGoodId + 255) % 256
     TotalMissing = TotalMissing + newMissing
     np.insert(list,i,np.zeros(newMissing,1) + np.nan)   
     i = i + newMissing
     list[i][0] = TotalMissing
     LastGoodId = pid 

---> 28 np.insert(list,i,np.zeros(newMissing,1) + np.nan) 29 i = i + newMissing 30 list[i][0] = TotalMissing

TypeError: data type not understood

有什么办法让我完成这个任务吗?在


Tags: 数据数量npzeros序列数组nanpid
2条回答

doc of ^{}

import numpy as np
a = np.arrray([(122.0, 1.0, -47.0), (123.0, 1.0, -47.0), (125.0, 1.0, -44.0)]))
np.insert(a, 2, np.nan, axis=0)
array([[ 122.,    1.,  -47.],
       [ 123.,    1.,  -47.],
       [  nan,   nan,   nan],
       [ 125.,    1.,  -44.]])

方法1

我们可以使用基于初始化的方法来处理多个间隙和任何长度的间隙-

# Pre-processing step to create monotonically increasing array for first col
id_arr = np.zeros(arr.shape[0])
id_arr[np.flatnonzero(np.diff(arr[:,0])<0)+1] = 256
a0 = id_arr.cumsum() + arr[:,0]

range_arr = np.arange(a0[0],a0[-1]+1)
out = np.full((range_arr.shape[0],arr.shape[1]),np.nan)
out[np.in1d(range_arr,a0)] = arr

样本运行-

^{2}$

方法2

可以建议另一种方法来使用np.insert而不是初始化来处理此类一般情况,如-

idx = np.flatnonzero(~np.in1d(range_arr,a0))
out = np.insert(arr,idx - np.arange(idx.size),np.nan,axis=0)

相关问题 更多 >