记录(2019年3月16日)机器学习基础——Numpy的使用【数组的合并与分割】(二)

本文详细介绍了使用NumPy进行数组的合并与分割操作,包括concatenate、vstack、hstack和split函数的用法,以及如何处理不同维度的数组拼接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import numpy as np
# 数组的合并操作
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
np.concatenate([x, y])
# 结果:[1, 2, 3, 4, 5, 6]

A = np.array([[1, 2, 3],
              [4, 5, 6]])
np.concatenate([A, A])
# 结果:
# [[1 2 3]
#  [4 5 6]
#  [1 2 3]
#  [4 5 6]]
# 沿着列方向进行拼接 axis:轴
np.concatenate([A, A], axis=1) 
# 结果:
# [[1 2 3 1 2 3]
#  [4 5 6 4 5 6]]

# np.concatenate方法不支持不同的维度,只能维度相同,若要拼接请转换成相同维度
z = np.array([666, 666, 666])
A = np.array([[1, 2, 3],
               [4, 5, 6]])
np.concatenate([A, z.reshape(1, -1)])
# 结果:
# [[  1   2   3]
#  [  4   5   6]
#  [666 666 666]]

# 比concatenate函数更好的垂直拼接方法:vstack
z = np.array([666, 666, 666])
A = np.array([[1, 2, 3],
               [4, 5, 6]])
np.vstack([A, z])
# 结果:
# [[  1   2   3]
#  [  4   5   6]
#  [666 666 666]]

# vstack函数的运用
A = np.array([[1, 2, 3],
               [4, 5, 6]])
B = np.full((2, 2), 100)
np.hstack([A, B])
# 结果:
# [[  1   2   3 100 100]
#  [  4   5   6 100 100]]

# 分割操作np.split
# 一维:
x = np.arange(10)
x1, x2, x3 = np.split(x, [3, 7])    # 分割成三段
# print(x1) :[0 1 2]
# print(x2) :[3 4 5 6]
# print(x3) :[7 8 9]

# 二维:
A = np.arange(16).reshape((4, 4))
# print(A) :[[ 0  1  2  3]
#             [ 4  5  6  7]
#             [ 8  9 10 11]
#             [12 13 14 15]
A1, A2 = np.split(A, [2])
# print(A1) :[[0 1 2 3]
#              [4 5 6 7]]
# print(A2):[[ 8  9 10 11]
#             [12 13 14 15]]

A1, A2 = np.split(A, [2], axis=1) # 列分割
# print(A1) :[[ 0  1]
#              [ 4  5]
#              [ 8  9]
#              [12 13]]
# print(A2) :[[ 2  3]
#              [ 6  7]
#              [10 11]
#              [14 15]]

# 更好的分割函数vsplit、hsplit
A = np.arange(16).reshape((4, 4))
upper, lower = np.vsplit(A, [2])
# print(upper) :[[0 1 2 3]
#              [4 5 6 7]]
# print(lower):[[ 8  9 10 11]
#             [12 13 14 15]]

left, right = np.hsplit(A, [2])
# print(left) :[[ 0  1]
#              [ 4  5]
#              [ 8  9]
#              [12 13]]
# print(right) :[[ 2  3]
#              [ 6  7]
#              [10 11]
#              [14 15]]

X, y = np.hsplit(A, [-1])
# print(X) :[[ 0  1  2]
#             [ 4  5  6]
#             [ 8  9 10]
#             [12 13 14]] 
# print(y ):[[ 3]
#             [ 7]
#             [11]
#             [15]]
# 将y变换成向量:行全部抽出
newY = y[:, 0]
# print(newY)
# [ 3  7 11 15]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值