在 Python 中连接矩阵的值

问题描述 投票:0回答:1

我有一个如下所示的矩阵,想要添加一个包含连接值的新列

# Sample matrix
matrix = np.array([[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9]])
python-3.x
1个回答
0
投票
import numpy as np

# Sample matrix
matrix = np.array([[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9]])

# If the values need to be summed up
# Concatenate the columns to create a new column
#new_column = np.sum(matrix, axis=1).reshape(-1, 1)

# Concatenate the columns to create a new column 

new_column = np.array([''.join(map(str, row)) for row in matrix]).reshape(-1, 1)

# Add the new column to the right side of the matrix
new_matrix = np.hstack((matrix, new_column))

print("Original matrix:")
print(matrix)
print("\nNew matrix with concatenated column:")
print(new_matrix)
© www.soinside.com 2019 - 2024. All rights reserved.