Python 将长度不等的列表重塑为numpy数组

Python 将长度不等的列表重塑为numpy数组,python,arrays,reshape,Python,Arrays,Reshape,我有一个带有dtype=object的特定数组,数组元素表示不同时间的坐标对,我想将其重塑为更简单的格式。 我“一次”成功地做到了这一点,但我不能让它对所有时间的观察都起作用 每个观察值的长度是不同的,所以也许我必须使用屏蔽值来实现这一点。 下面是一个例子,我希望能更好地解释我想要什么 # My "input" is: a = np.array([[], [(2, 0), (2, 2)], [(2, 2), (2, 0), (2, 1), (2, 2)]], dtype=object) #An

我有一个带有
dtype=object
的特定数组,数组元素表示不同时间的坐标对,我想将其重塑为更简单的格式。 我“一次”成功地做到了这一点,但我不能让它对所有时间的观察都起作用

每个观察值的长度是不同的,所以也许我必须使用屏蔽值来实现这一点。 下面是一个例子,我希望能更好地解释我想要什么

# My "input" is:
a = np.array([[], [(2, 0), (2, 2)], [(2, 2), (2, 0), (2, 1), (2, 2)]], dtype=object)

#And my "output" is:

#holding_array_VBPnegl
array([[2, 0],
       [2, 2],
       [2, 1]])

#It doesnt consider my for loop in a.shape[0], so the expected result is :
test = np.array([[[True, True],
       [True, True],
       [True, True]],

       [[2, 0],
       [2, 2],
       [True, True]]

       [[2, 0],
       [2, 2],
       [2, 1]]])

#with "True" the masked values
我已尝试使用在StackOverflow上找到的代码:

import numpy as np

holding_list_VBPnegl=[]
for i in range(a.shape[0]):
    for x in a[i]:
        if x in holding_list_VBPnegl:
            pass
        else:
            holding_list_VBPnegl.append(x)

print holding_list_VBPnegl
holding_array_VBPnegl = np.asarray(holding_list_VBPnegl)

Numpy阵列最适合用于连续内存块,因此首先需要预先分配所需的内存量。您可以从数组
a
的长度(我很乐意将其转换为一个列表-不要滥用numpy数组来存储长度不等的列表)和最长观察的长度(在本例中为4,
a
的最后一个元素)中获得这一结果

现在您已经预先分配了所需的内容,并将阵列设置为可以进行掩蔽。您现在只需使用已有的数据填充阵列:

for rowind, row in enumerate(s):
    try:
        m[rowind, :len(row),:] = np.array(row)
    except ValueError:
        pass  # broadcasting error: row is empty

result = np.ma.masked_array(m.astype(np.int), mask=np.isnan(m))
result
masked_array(data =
 [[[-- --]
  [-- --]
  [-- --]
  [-- --]]

 [[2 0]
  [2 2]
  [-- --]
  [-- --]]

 [[2 2]
  [2 0]
  [2 1]
  [2 2]]],
             mask =
 [[[ True  True]
  [ True  True]
  [ True  True]
  [ True  True]]

 [[False False]
  [False False]
  [ True  True]
  [ True  True]]

 [[False False]
  [False False]
  [False False]
  [False False]]],
       fill_value = 999999)

您的
测试
数组与您的输入
a
之间没有相关性。请编辑您的问题(需要在
a
中删除
(2,2)
元组中的一个元组,使其看起来类似于
test
,但其他元组的顺序也需要更改)。非常感谢您的帮助!;)
for rowind, row in enumerate(s):
    try:
        m[rowind, :len(row),:] = np.array(row)
    except ValueError:
        pass  # broadcasting error: row is empty

result = np.ma.masked_array(m.astype(np.int), mask=np.isnan(m))
result
masked_array(data =
 [[[-- --]
  [-- --]
  [-- --]
  [-- --]]

 [[2 0]
  [2 2]
  [-- --]
  [-- --]]

 [[2 2]
  [2 0]
  [2 1]
  [2 2]]],
             mask =
 [[[ True  True]
  [ True  True]
  [ True  True]
  [ True  True]]

 [[False False]
  [False False]
  [ True  True]
  [ True  True]]

 [[False False]
  [False False]
  [False False]
  [False False]]],
       fill_value = 999999)