【问题标题】:Reshape list of unequal length lists into numpy array将不等长列表的列表重塑为 numpy 数组
【发布时间】:2014-11-12 14:59:24
【问题描述】:

我有一个带有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)

【问题讨论】:

  • 您的test 数组和您的输入a 之间没有关联。请编辑您的问题(需要在a 中删除(2,2) 元组之一,使其看起来类似于test,但其他元组的顺序也需要更改)。

标签: python arrays reshape


【解决方案1】:

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

import numpy as np
a = np.array([[], [(2, 0), (2, 2)], [(2, 2), (2, 0), (2, 1), (2, 2)]], dtype=object)

s = a.tolist()  # Lists are a better container type for your data...
cols = len(s)
rows = max( len(l) for l in s)

m = np.ones((cols, rows, 2))*np.nan

现在您已经预先分配了所需的内容并设置了数组以进行屏蔽。您现在只需要用已有的数据填充数组:

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)

【讨论】:

  • 非常感谢您的帮助! ;)
猜你喜欢
  • 2021-03-21
  • 1970-01-01
  • 2019-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-13
  • 1970-01-01
相关资源
最近更新 更多