The desired array has a different shape than the original array, a.
Therefore, you can not generate the desired array by using simple slice
assignment, or a single call to assignment functions like numpy.place, numpy.put, numpy.putmask
or numpy.copyto.
So instead of regarding this as an assignment-and-insertion operation, I think
it might be better to regard this as construction of a new array.
There are many ways to do this:
You could use numpy.concatenate:
np.concatenate([a[:,:1], b, a[:,2:]], axis=1)
or numpy.column_stack:
np.column_stack([a[:,:1], b, a[:,2:]])
or numpy.c_:
np.c_[a[:,:1], b, a[:,2:]]
or numpy.bmat:
np.array(np.bmat([a[:,:1], b, a[:,2:]]))
or allocate space for an empty array and assign values to slices of c:
c = np.empty((a.shape[0], a.shape[1]+b.shape[1]-1), dtype=a.dtype)
c[:, :1] = a[:, :1]
c[:, 1:4] = b
c[:, 4:] = a[:, 2:]
This is not necessary here, but it is good to keep in mind that allocate-and-assign is a viable way to construct arrays. Sometimes, though not here, it is even your fastest option.
or numpy.delete and numpy.insert:
np.insert(np.delete(a, [1], 1), [1], b, axis=1)
I don't recommend using insert and delete however. The np.delete creates a new array with
values that are copied from a. In contrast, the slices a[:,:1], and
a[:,2:] are views of a so they do not require any copying. The extra
allocation and copying makes this method slower than the other methods shown
above.
For example, if we define:
import numpy as np
a = np.array([[ 0., 2., 0., 0., 0., 0.],
[ 0., 14., 0., 0., 0., 0.]])
b = np.array([(1, 0, 0),
(0, 0, 1)])
then
In [69]: np.concatenate([a[:,:1],b,a[:,2:]], axis=1)
Out[69]:
array([[ 0., 1., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 1., 0., 0., 0., 0.]])
(The other options produce the same result.)
place(), see docs.scipy.org/doc/numpy/reference/generated/numpy.place.html2you are replacing a value. For14you are replacing a value (with 0) and inserting a (2,2) array. Two different actions.