numpy-添加操作大全

合并

hstack(tup):按行合并  【前面有个 h,可以理解为 行,这样方便记忆】

vstack(tup):按列合并

参数虽然是 tuple,但是 list 也行,可以合并2个或者多个数组。

a=np.floor(10*np.random.rand(2,2))
b=np.floor(10*np.random.rand(2,2))

### hstack()在行上合并
np.hstack((a,b))
# array([[ 8.,  5.,  1.,  9.],
#        [ 1.,  6.,  8.,  5.]])

#### vstack()在列上合并
np.vstack((a,b))
# array([[ 8.,  5.],
#        [ 1.,  6.],
#        [ 1.,  9.],
#        [ 8.,  5.]])


print np.vstack([a,b,b])        # list 参数
# [[ 1.  4.]        a
#  [ 9.  5.]
#  [ 7.  6.]        b
#  [ 2.  9.]
#  [ 7.  6.]        b
#  [ 2.  9.]]

追加

append(arr, values, axis=None):可以追加数组,也可以追加数字,追加数组相当于合并。

arr 分为一维和二维

一维:只有一个方向,故只能在一个维度上追加

二维:两个二维数组,拼接方向上 shape 必须一致

二者皆可追加数字,不管前面的shape是什么,注意输出都是一维数组。

二维1表示按行拼接,0表示按列拼接,不好记,到时候试试算了。

##  一维
# 一维相当于只有一个维度,故不能在另一个维度上操作
y = np.array([1, 2])
z = np.array([3, 4])
out1 = np.append(y, z, axis=0)
print(out1)             # [1 2 3 4]
# out2 = np.append(y, z, axis=1)        # numpy.AxisError: axis 1 is out of bounds for array of dimension 1
# print(out2)

# 直接拼数字
print np.append(y, 3)       # [1 2 3]


## 二维
y = np.array([[1, 2]])
z = np.array([[3, 4]])
out3 = np.append(y, z, axis=0)
print(out3)
# [[1 2]
#  [3 4]]
out4 = np.append(y, z, axis=1)
print(out4)             # [[1 2 3 4]]

m = np.array([[3, 4, 5]])
out5 = np.append(y, m, axis=1)      # [[1 2 3 4 5]]
print(out5)

# 直接拼数字,输出为一维
print np.append(y, 3)   # [1 2 3]
print np.append(np.empty([0, 0]), 3)        # [3.]
原文地址:https://www.cnblogs.com/yanshw/p/11382123.html