numpy.insert


此函数沿给定轴和给定索引之前在输入数组中插入值。如果将值的类型转换为插入,则它与输入数组不同。插入没有到位,函数返回一个新数组。此外,如果未提及轴,则输入数组变平。

insert()函数采用以下参数

numpy.insert(arr, obj, values, axis)

这里

序号 参数和描述
1 arr 输入数组
2 obj 要进行插入的索引
3 values 要插入的值数组
4 axis 要插入的轴。如果没有给出,则输入数组被展平

import numpy as np
a = np.array([[1,2],[3,4],[5,6]])

print 'First array:'
print a
print '\n'  

print 'Axis parameter not passed. The input array is flattened before insertion.'
print np.insert(a,3,[11,12])
print '\n'  
print 'Axis parameter passed. The values array is broadcast to match input array.'

print 'Broadcast along axis 0:'
print np.insert(a,1,[11],axis = 0)
print '\n'  

print 'Broadcast along axis 1:'
print np.insert(a,1,11,axis = 1)

其输出如下

First array:
[[1 2]
 [3 4]
 [5 6]]

Axis parameter not passed. The input array is flattened before insertion.
[ 1 2 3 11 12 4 5 6]

Axis parameter passed. The values array is broadcast to match input array.
Broadcast along axis 0:
[[ 1 2]
 [11 11]
 [ 3 4]
 [ 5 6]]

Broadcast along axis 1:
[[ 1 11 2]
 [ 3 11 4]
 [ 5 11 6]]