深度阅读

How to concatenate arrays in python

作者
作者
2023年08月22日
更新时间
12.48 分钟
阅读时间
0
阅读量

To concatenate arrays in Python, you can use the numpy.concatenate() function if you have NumPy arrays, or the + operator if you have lists. Here are some examples:

For NumPy arrays:

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

This will output [1 2 3 4 5 6], which indicates that the arrays have been concatenated along the first axis.

If you have arrays with different dimensions, you can specify the axis parameter to indicate the axis along which to concatenate the arrays. For example:

import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
c = np.concatenate([a, b], axis=0)
print(c)

This will output [[1 2] [3 4] [5 6]], which indicates that the arrays have been concatenated vertically along the first axis.

For regular Python lists, you can simply use the + operator to concatenate them:

a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)

This will output [1, 2, 3, 4, 5, 6], which indicates that the lists have been concatenated.

Note that if you are concatenating lists or arrays of different types, you may need to perform some type conversion to ensure that the concatenated result is of the desired type.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。