[英]How to convert a list of numpy arrays with empty arrays into a single array?
So my data looks like:所以我的数据看起来像:
[array([0], dtype=int64),
array([1], dtype=int64),
array([1], dtype=int64),
array([2], dtype=int64),
array([3], dtype=int64),
array([3], dtype=int64),
array([4], dtype=int64),
array([], dtype=int64),
array([], dtype=int64),
array([], dtype=int64),
array([], dtype=int64),
array([], dtype=int64),
array([], dtype=int64),
array([], dtype=int64),
array([], dtype=int64),
array([], dtype=int64),
array([], dtype=int64),
array([], dtype=int64),
array([], dtype=int64),
array([], dtype=int64),
array([6], dtype=int64) ...
While using np.concatenate(list_1)
does concatenate the arrays but skips the empty arrays.虽然使用
np.concatenate(list_1)
确实连接了 arrays 但跳过了空的 arrays。 And in tthe resultant array 6 is the next element to 4 and intermediate empty arrays does not appear in the list.结果数组 6 是 4 的下一个元素,中间的空 arrays 没有出现在列表中。 This is what np.concateneate does but I do not want it that way.
这就是 np.concateneate 所做的,但我不希望这样。
I want to combine those arrays into a single array having same length as the list but NaN
values in place of empty arrays.我想将这些 arrays 组合成一个与列表具有相同长度但
NaN
值代替空 arrays 的数组。 How can I achieve that?我怎样才能做到这一点?
One way:单程:
np.concatenate([a if a.size else np.array([np.nan]) for a in array_list])
I would hazard a guess though there is probably a better way to load your data.尽管可能有更好的方法来加载您的数据,但我会冒险猜测。
As a side note, concatenate
does not skip any array - it concatenates the arrays, that is, puts the elements for each one after the other.作为旁注,
concatenate
不会跳过任何数组 - 它连接 arrays,也就是说,将每个元素一个接一个地放置。 Placing 0 elements is just not noticeable.放置 0 个元素并不明显。
You can pre-allocate the output and assign to it directly:您可以预先分配 output 并直接分配给它:
result = np.full(len(list_1), np.nan)
for i, v in enumerate(list_1):
if v.size:
result[i] = v.item()
Alternatively, you can do或者,你可以做
result = np.empty(len(list_1))
for i, v in enumerate(list_1):
result[i] = v.item() if v.size else np.nan
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.