假设您有一个可变长度列表数组a:
>>> import numpy as np
>>> import awkward as ak
>>> a = ak.Array([[0, 1, 2], [], [3, 4], [5], [6, 7, 8, 9]])
>>> a
<Array [[0, 1, 2], [], ... [5], [6, 7, 8, 9]] type='5 * var * int64'>
使所有列表具有相同大小的函数是ak.pad_none。但首先,我们需要一个尺寸来填充它。我们可以用ak.num得到每个列表的长度,然后取其中的np.max。
>>> ak.num(a)
<Array [3, 0, 2, 1, 4] type='5 * int64'>
>>> desired_length = np.max(ak.num(a))
>>> desired_length
4
现在我们可以填充它并将其转换为 NumPy 数组(因为它现在具有矩形形状)。
>>> ak.pad_none(a, desired_length)
<Array [[0, 1, 2, None], ... [6, 7, 8, 9]] type='5 * var * ?int64'>
>>> ak.to_numpy(ak.pad_none(a, desired_length))
masked_array(
data=[[0, 1, 2, --],
[--, --, --, --],
[3, 4, --, --],
[5, --, --, --],
[6, 7, 8, 9]],
mask=[[False, False, False, True],
[ True, True, True, True],
[False, False, True, True],
[False, True, True, True],
[False, False, False, False]],
fill_value=999999)
缺失值 (None) 被转换为 NumPy 掩码数组。如果你想要一个普通的 NumPy 数组,你可以ak.fill_none 给它们一个替换值。
>>> ak.to_numpy(ak.fill_none(ak.pad_none(a, desired_length), 999))
array([[ 0, 1, 2, 999],
[999, 999, 999, 999],
[ 3, 4, 999, 999],
[ 5, 999, 999, 999],
[ 6, 7, 8, 9]])