用不同维度的子数组展平numpy数组 [英] Flatten numpy array with sub-arrays of different dimensions

查看:134
本文介绍了用不同维度的子数组展平numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎很简单,但是我还没有找到如何使用numpy来完成的任务.考虑示例数组:

This seems like a simple enough task, but I haven't found how to do it using numpy. Consider the example array:

import numpy as np
aa = np.array([np.array([13.16]), np.array([1.58 , 1.2]), np.array([13.1]), np.array([1. , 2.6])], dtype=object)

我需要一种通用的方法来使用N=every float in all the sub-arrays将那个数组展平为N个元素的单个数组.在这种情况下,将是:

I need a general way to flatten that array into a single array of N elements, with N=every float in all the sub-arrays. In this case it would be:

aa = np.array([13.16, 1.58 , 1.2, 13.1, 1. , 2.6])

我已经尝试过np.ndarray.flatten()(尝试了所有的"order"选项),但是我又得到了相同的未更改的aa数组.

I've tried np.ndarray.flatten() (tried all the 'order' options)) but I get back the same unchanged aa array.

为什么np.ndarray.flatten()无法正常工作,我该怎么做?

Why is np.ndarray.flatten() not working and how can I accomplish this?

该解决方案应尽可能通用,因为我在此处使用的示例aa数组实际上将在我的真实代码中充满不同长度的子数组.

The solution should be as general as possible since the example aa array I'm using here will actually be filled with sub-arrays of different lengths in my real code.

推荐答案

您可以使用 numpy.hstack

You can use numpy.hstack

>>> np.hstack(aa)
array([13.16,  1.58,  1.2 , 13.1 ,  1.  ,  2.6 ])

这篇关于用不同维度的子数组展平numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆