如何将一维数组作为列转换为Python中的二维数组?
让我们看一个使用Python中的 NumPy 库将一维数组作为列转换为二维数组的程序。因此,为了解决这个问题,我们使用 NumPy 的numpy.column_stack()函数。此函数采用一维数组序列并将它们堆叠为列以形成单个二维数组。
Syntax : numpy.column_stack(tuple)
Parameters :
tup : [sequence of ndarrays] Tuple containing arrays to be stacked. The arrays must have the same first dimension.
Return : [stacked 2-D array] The stacked 2-D array of the input arrays.
现在,让我们看一个例子:
示例 1:
Python3
# import library
import numpy as np
# create a 1d-array
a = np.array(("Geeks", "for",
"geeks"))
# create a 1d-array
b = np.array(("my", "name",
"sachin"))
# convert 1d-arrays into
# columns of 2d-array
c = np.column_stack((a, b))
print(c)
Python3
# import library
import numpy as np
# create 1d-array
a = np.array((1,2,3,4))
# create 1d-array
b = np.array((5,6,7,8))
# convert 1d-arrays into
# columns of 2d-array
c = np.column_stack((a, b))
print(c)
输出:
[['Geeks' 'my']
['for' 'name']
['geeks' 'sachin']]
示例 2:
Python3
# import library
import numpy as np
# create 1d-array
a = np.array((1,2,3,4))
# create 1d-array
b = np.array((5,6,7,8))
# convert 1d-arrays into
# columns of 2d-array
c = np.column_stack((a, b))
print(c)
输出:
[[1 5]
[2 6]
[3 7]
[4 8]]