简体   繁体   中英

How to insert an array into existing multi-dimensional array by index? [Python]

I manipulated the MNIST dataset for research, by adding a set of digits to each digit in the dataset.

Before manipulation:

In:
x_train.shape

Out: 
(60000, 28, 28)

Expectated result after manipulation:

In:
x_train_new.shape

Out: 
(60000, 11, 28, 28)

However I messed up and forgot to add x_train[i] in each iteration. Therefore my shape is the following:

In:
x_train_new.shape

Out: 
(60000, 10, 28, 28)

I have tried to apply np.insert , however I am struggling to apply it correctly since it is a multidimensional array:

tryout = x_train_new[0]

In:
np.insert(tryout, 0, x_train[0])

Out:
ValueError: could not broadcast input array from shape (28,28) into shape (28)

How can I insert x_train[i] to each ``ì```? Is it possible to insert the array as the first value in each array?

Any help is appreciated. Thank you very much.

Just create an empty array

x_train_expected = np.empty((60000, 11, 28, 28))

and do

x_train_expected[:,1:] = x_train_new
x_train_expected[:,0] = x_train

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM