简体   繁体   English

二维列表到 ndarray 的 np.ndarray

[英]2D list to np.ndarray of ndarray

I have a 2D list like this我有一个像这样的二维列表

import numpy as np
data=[[1,2],[2,3],[3,4]]

I want to turn this to np.ndarray.我想把它变成 np.ndarray。

I don't want to get this:我不想得到这个:

np.array(data).shape
#(3,2)

my expected is like this我的期望是这样的

result=np.array(np.array([1,2]),np.array([2,3]),np.array([3,4]))

result.dtype
result.shape
#np.ndarry
#(3,)
result[i].shape
result[i].dtype
#(2,)
#np.ndarry

what should i do this a lot我应该怎么办

AS @hpaulj suggested in comments AS @hpaulj 在评论中建议
You can create firstempty array of object type and then assign list to it like您可以创建object类型的第一个empty数组,然后将列表分配给它

data = [[1,2],[2,3],[3,4]]
result = np.empty(shape=len(data), dtype=object)

result[:] = [np.array(i) for i in data]
result
array([array([1, 2]), array([2, 3]), array([3, 4])], dtype=object)

result.shape
(3,)

You can try converting the list into an ndarray and then flattening it您可以尝试将列表转换为 ndarray,然后将其展平

np.array(data).flatten()

You can also specify order parameter in flatten to flatten in row-major ('C') or column-major ('F') order您还可以在 flatten 中指定 order 参数以按行优先('C')或列优先('F')顺序展平

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM