[英]Python array using numpy
I am confused about doing vectorization using numpy
. 我对使用
numpy
进行矢量化感到困惑。
In particular, I have a matrix of this form: of type <type 'list'>
特别是,我有一个这种形式的矩阵:类型为
<type 'list'>
[[0.0, 0.0, 0.0, 0.0], [0.02, 0.04, 0.0325, 0.04], [1, 2, 3, 4]]
How do I make it look like the following using numpy? 如何使用numpy使它看起来像以下内容?
[[ 0.0 0.0 0.0 0.0 ]
[ 0.02 0.04 0.0325 0.04 ]
[ 1 2 3 4 ]]
Yes, I know I can do it using: 是的,我知道我可以使用:
np.array([[0.0, 0.0, 0.0, 0.0], [0.02, 0.04, 0.0325, 0.04], [1, 2, 3, 4]])
But I have a very long matrix, and I can't just type out each rows like that. 但是我有一个很长的矩阵,我不能只是像这样输入每一行。 How can I handle the case when I have a very long matrix?
如果矩阵很长,该如何处理?
This is not a matrix of type list, it is a list that contains lists. 这不是类型列表的矩阵,而是包含列表的列表。 You may think of it as matrix, but to Python it is just a list
您可能将其视为矩阵,但对于Python来说,它只是一个列表
alist = [[0.0, 0.0, 0.0, 0.0], [0.02, 0.04, 0.0325, 0.04], [1, 2, 3, 4]]
arr = np.array(alist)
works just the same as 的工作原理与
arr = np.array([[0.0, 0.0, 0.0, 0.0], [0.02, 0.04, 0.0325, 0.04], [1, 2, 3, 4]])
This creates 2d array, with shape (3,4) and dtype float 这将创建具有形状(3,4)和dtype float的2d数组
In [212]: arr = np.array([[0.0, 0.0, 0.0, 0.0], [0.02, 0.04, 0.0325, 0.04], [1, 2, 3, 4]])
In [213]: arr
Out[213]:
array([[ 0. , 0. , 0. , 0. ],
[ 0.02 , 0.04 , 0.0325, 0.04 ],
[ 1. , 2. , 3. , 4. ]])
In [214]: print(arr)
[[ 0. 0. 0. 0. ]
[ 0.02 0.04 0.0325 0.04 ]
[ 1. 2. 3. 4. ]]
Assuming you start with a large array, why not split it into arrays of the right size ( n
): 假设您从一个大数组开始,为什么不将其拆分为大小合适的数组(
n
):
splitted = [l[i:i + n] for i in range(0, len(array), n)]
and make the matrix from that: 并从中得出矩阵:
np.array(splitted)
If you're saying you have a list of lists stored in Python object A
, all you need to do is call np.array(A)
which will return a numpy array using the elements of A
. 如果您说有一个存储在Python对象
A
中的列表列表,则只需调用np.array(A)
,它将使用A
的元素返回一个numpy数组。 Otherwise, you need to specify what form your data is in right now to clarify how you want to load your data. 否则,您需要指定数据现在的格式,以阐明您要如何加载数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.