numpy数组从一个异构的字典

iyr7buue  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(180)

假设我有一个这样的法令:

exampledict = {0: np.array([1,2,3,4]), 1: np.array([1,2,3])}

我想做的是把它变成一个numpy数组。虽然dict中两个数组的形状不一致,但我想知道,当没有足够的元素时,是否有一种方法可以将其变成一个填充零的2D数组,使其看起来像这样:
[[1、2、3、4]、[1、2、3、0]]
这样做的原因是dict实际上有很多键值对,我希望在后续的计算密集型中避免for循环。
先谢谢你了!

  • 亚西尔

我试过了

np.array(list(exampledict.values()))

失败并出现错误ValueError:用序列设置数组元素。请求的数组在1维之后具有不均匀的形状。检测到的形状为(2,)+不均匀部分。

s3fp2yjn

s3fp2yjn1#

如果你想使用pandas

import pandas as pd

a = (pd.DataFrame.from_dict(exampledict, orient='index')
       .fillna(0, downcast='infer').to_numpy()
     )

itertools.zip_longest

from itertools import zip_longest

a = np.array(list(zip_longest(*exampledict.values(), fillvalue=0))).T

输出:

array([[1, 2, 3, 4],
       [1, 2, 3, 0]])

相关问题