首页 > 解决方案 > Numpy数组:删除和附加值

问题描述

我有一个形状的 3D numpy 数组(1, 60, 1)。现在我需要删除第二个维度的第一个值,而是在末尾附加一个新值。

如果它是一个列表,代码看起来有点像这样:

x = [1, 2, 3, 4]
x = x[1:]
x.append(5)

产生这个列表:[2, 3, 4, 5]

用 numpy 做到这一点的最简单方法是什么?

我以前基本上从未真正使用过 numpy,所以这可能是一个非常微不足道的问题,但感谢您的帮助!

标签: pythonnumpynumpy-ndarray

解决方案


import numpy as np

arr = np.arange(60)   #creating a nd array with 60 values  
arr = arr.reshape(1,60,1)   # shaping it as mentiond in question
arr = np.roll(arr, -1)   # use np.roll to circulate the array left or right (-1 is 1 step to the left)
#Now your last value is in the second last position, the second last value in the third last pos and so on (Your first value moves to the last position)  
arr[:,-1,:] = 1000  # index the last location and add the values you want  
print(arr)

推荐阅读