我有一个形状为(1, 100)
的数组,即:
[[1. 2. 3. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 55.]]
我想在末尾添加一些内容(例如,像123
这样的数字,并删除第一个元素,这样我就可以了:
[[2. 3. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 55. 123.]]
保留原始形状(1, 100)
我正在尝试:
x_pred = np.append(x_pred, next_index, axis=1)
({x_pred
是(1, 100)
数组,而next_index
是标量)
但是我得到一个错误:
ValueError: all the input arrays must have same number of dimensions
我在做什么错了?
答案 0 :(得分:2)
您可以使用roll
进行此操作。
a = np.zeros((1,10))
#roll and replace
a[0] = np.roll(a[0],-1)
a[0][-1] = new_value
答案 1 :(得分:1)
import numpy as np
x_pred = np.zeros((1,100))
x_pred = np.insert(x_pred, x_pred.size, 123, 1)
x_pred = np.delete(x_pred, 0, axis=1)
x_pred打印:
array([[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
123.]])
大小为100
以下不适用于二维数组,但对于一维数组正确:
使用numpy插入,您可以执行此操作
import numpy as np
tmp = np.array([0,1,2,3])
tmp = np.insert(tmp[1:], tmp.size-1, 123)
# [ 1, 2, 3, 123]
或更像您的示例
import numpy as np
tmp = np.array([0,0,0,0])
tmp = np.insert(tmp[1:], tmp.size-1, 123)
# [ 0, 0, 0, 123]
在np.insert()
中,第一个参数是要插入的数组,第二个参数是要插入的索引,第三个参数是要插入的值。
tmp[1:]
只是说出第一个元素(即第0个元素)到末尾的所有内容。
x_pred = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,])
x_pred = np.insert(x_pred[1:], x_pred.size-1, 123)
x_pred
打印:
array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 123])
和
x_pred.size
打印100
答案 2 :(得分:1)
追加作为列表中的列表,以使其具有相同的维数:
npx cypress run -b chrome
或
>>> a = np.array([[0,1,2,3]])
>>> a
array([[0, 1, 2, 3]])
>>> q = 123
>>> np.append(a[:,1:],[[q]], axis=1)
array([[ 1, 2, 3, 123]])
>>>