简体   繁体   English

带有dtype = int32的值列表转换为np.array对象的Dict

[英]Dict with list of values convert to np.array object with dtype=int32

I have a dictionary {0: [], 1: [], ...} . 我有一本字典{0: [], 1: [], ...} The length of every list is different. 每个列表的长度都不同。
How to convert such a dictionary to np.array object? 如何将这样的字典转换为np.array对象?
I want to get such a structure: array([[],[],..., dtype=int32) 我想得到这样一个结构: array([[],[],..., dtype=int32)

have you tried this ? 你试过这个吗?

np.array(list(d.values()))

ouput 输出中

array([], shape=(2, 0), dtype=float64)

Strangely, putting the dict into the numpy array works. 奇怪的是,将dict放入numpy数组中是有效的。 Also putting the listed values into the array works. 同时将列出的值放入数组中也可以。

import numpy as np

d = {0: [1, 2], 1: [3, 6, 7]}
arr = np.array(d)
print(arr)
li = d.values()
print(li)
arr2 = np.array(li)
print(arr2)

If the lists are of different lengths you could use a np.ma.MaskedArray : 如果列表长度不同,您可以使用np.ma.MaskedArray

import numpy as np

maxlen = max(len(lst) for lst in d.values())   # maximum length of all value-lists

arr = np.ma.MaskedArray(np.zeros((len(d), maxlen), dtype='int32'), 
                        mask=True, 
                        dtype='int32')

for line, lst in d.items():
    arr[line, :len(lst)] = lst

# In case the "keys" of your dictionary don't represent the "rows" you need to
# use another (more robust) approach:
# for idx, (line, lst) in enumerate(sorted(d.items())):
#     arr[idx, :len(lst)] = lst

For example: 例如:

d = {0: [], 1: [1], 2: [1, 2]}

Gives an arr like this: 给出这样的arr

masked_array(data =
 [[-- --]
 [1 --]
 [1 2]],
             mask =
 [[ True  True]
 [False  True]
 [False False]],
       fill_value = 999999)

It won't be the same as having empty lists but NumPy doesn't support ragged arrays so MaskedArray is one of the possible ways to "simulate" them. 它与空列表不同,但NumPy不支持不规则数组,因此MaskedArray是“模拟”它们的可能方法之一。 For most purposes they will behave like an "ragged array". 在大多数情况下,它们的行为就像一个“粗糙的阵列”。 :) :)

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

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