无法使用numpy展平数组

时间:2019-01-07 19:01:12

标签: python arrays numpy

我的输出如下:

data = [array([1.        , 1.14112001, 0.7205845 , 1.41211849, 0.46342708,
        1.65028784, 0.24901275]),
 array([1.83665564, 0.09442164, 1.95637593, 0.01196838, 1.99991186,
        0.00822115, 1.96379539]),
 array([0.08347845, 1.85090352, 0.23174534, 1.67022918, 0.44121095,
        1.43616476])]

这是3个数组的列表。我必须展平阵列。这应该很简单,例如data.flatten("F") 但这不起作用

输出应包含每个数组的第一个元素,然后是第二个,依此类推。

类似:1,1.83665564,1.14112001,0.09442164,1.85090352,依此类推。我该怎么办

更新:

我使用给定代码得到的输出如下

array([array([1.        , 1.14112001, 0.7205845 , 1.41211849, 0.46342708,
       1.65028784, 0.24901275]),
       array([1.83665564, 0.09442164, 1.95637593, 0.01196838, 1.99991186,
       0.00822115, 1.96379539]),
       array([0.08347845, 1.85090352, 0.23174534, 1.67022918, 0.44121095,
       1.43616476])], dtype=object)

3 个答案:

答案 0 :(得分:1)

<% for (const products of pending) { %>
 <li>
    <a href="#" class="button gray delete" data-id="<%= products._id %>"><i class="sl sl-icon-close"></i> Delete</a>
 </li>
<% } %>

<script>
    const deleteBtn = document.querySelector('.delete');
    const productId = deleteBtn.getAttribute('data-id');
    document.querySelector('.delete').addEventListener('click', e => {
        e.preventDefault();
        alert(productId);
    });
</script>

输出:

from numpy import array
data = [array([1.        , 1.14112001, 0.7205845 , 1.41211849, 0.46342708,
        1.65028784, 0.24901275]),
 array([1.83665564, 0.09442164, 1.95637593, 0.01196838, 1.99991186,
        0.00822115, 1.96379539]),
 array([0.08347845, 1.85090352, 0.23174534, 1.67022918, 0.44121095,
        1.43616476])]
max=len(max(data,key=len))
final_list=[]
for index in range (0,max):
        final_list.extend([a[index] for a in data if len(a)>index])
print(final_list)

答案 1 :(得分:1)

不知道最好的解决方案,但是您可以使用np.resize将所有数组整形为相同的长度并垂直堆叠。然后使用.T使它们变平,并使用掩码排除由np.resize创建的值:

l = max(x.size for x in data)
masks = [np.arange(l) < x.size for x in data]
np.vstack(np.resize(x, l) for x in data).T.flatten()[np.vstack(masks).T.flatten()]

>> array([1.        , 1.83665564, 0.08347845, 1.14112001, 0.09442164,
   1.85090352, 0.7205845 , 1.95637593, 0.23174534, 1.41211849,
   0.01196838, 1.67022918, 0.46342708, 1.99991186, 0.44121095,
   1.65028784, 0.00822115, 1.43616476, 0.24901275, 1.96379539])

答案 2 :(得分:1)

使用itertools.zip_longest依次获取不同长度数组中的元素(请参见this post),然后使用列表推导来展平结果元组。

在Python 2中,我们应该改用itertools.izip_longest。

>>> from itertools import zip_longest
>>> from numpy import array

# three sample arrays make up a list from 1 to 11
>>> data = array([array([1,4,7,10]), array([2,5,8,11]), array([3,6,9])])
>>> temp = list(zip_longest(*data, fillvalue=None))
>>> temp
[(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, None)]

>>> [i for tup in temp for i in tup if i is not None]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]