如何在开始时在 ndarray 中插入数字 (i+1)?

问题描述

我在 npz 文件中有 ndarray,我试图在索引 0 处插入数字,插入的数字应该增加 1。 下面是我的数组

data = [[[3.56,7.94,1.78],[8.23,1.25,4.80],[0.51,8.23,5.67],[9.56,2.78],[5.23,7.25,0.80],...]]

结果 ndarray 应该像

data = [[[0,3.56,[1,[2,0.51,[3,9.56,[4,5.23,...]]

我是这个领域的新手,所以我需要一些帮助来解决这个问题。

此外,我尝试了 this solution 但它用于一维数组。

我的示例代码

import numpy as np

a = np.load('abc.npz')['data']
b = a.insert(a,0+1) # I'm confused here
np.savez('new.npz',data=b)

寻求一些建议

解决方法

你应该这样做:

import numpy as np

data = np.array([[[3.56,7.94,1.78],[8.23,1.25,4.80],[0.51,8.23,5.67],[9.56,2.78],[5.23,7.25,0.80]]])

res = np.insert(data,np.arange(data.shape[1]),axis=2)
print(res)

输出

[[[0.   3.56 7.94 1.78]
  [1.   8.23 1.25 4.8 ]
  [2.   0.51 8.23 5.67]
  [3.   9.56 7.94 2.78]
  [4.   5.23 7.25 0.8 ]]]

从文档中,insert

在给定索引之前沿给定轴插入值。

所以基本上你需要指定数组 (data)、索引 (0)、要插入的值 (np.arange(data.shape[1])) 和轴。

,

我已经解决了我的问题。 Dani Mesejo 帮助了我,我从他那里得到了一些想法。

以下是解决方案

data = data.tolist()
for index,d in enumerate(data[:]): # slicing
    d.insert(0,index) # insert numbers in 0 index of every list.

我们的想法是将ndarray转换为list,然后我们可以在序列化后将其保存在npz或json中