Python 数组到一维向量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18048646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:48:13  来源:igfitidea点击:

Python array to 1-D Vector

pythonnumpy

提问by Abhishek Thakur

Is there a pythonic way to convert a structured array to vector?

是否有将结构化数组转换为向量的pythonic方法?

For example:

例如:

I'm trying to convert an array like:

我正在尝试转换一个数组,如:

[(9,), (1,), (1, 12), (9,), (8,)]

to a vector like:

到一个向量,如:

[9,1,1,12,9,8]

采纳答案by unutbu

In [15]: import numpy as np

In [16]: x = np.array([(9,), (1,), (1, 12), (9,), (8,)])

In [17]: np.concatenate(x)
Out[17]: array([ 9,  1,  1, 12,  9,  8])

Another option is np.hstack(x), but for this purpose, np.concatenateis faster:

另一种选择是np.hstack(x),但为此目的,np.concatenate速度更快:

In [14]: x = [tuple(np.random.randint(10, size=np.random.randint(10))) for i in range(10**4)]

In [15]: %timeit np.hstack(x)
10 loops, best of 3: 40.5 ms per loop

In [16]: %timeit np.concatenate(x)
100 loops, best of 3: 13.6 ms per loop

回答by zs2020

You don't need to use any numpy, you can use sum:

您不需要使用 any numpy,您可以使用sum

myList = [(9,), (1,), (1, 12), (9,), (8,)]
list(sum(myList, ()))

result:

结果:

[9, 1, 1, 12, 9, 8]

回答by PSN

Use numpy .flatten()method

使用 numpy.flatten()方法

>>> a = np.array([[1,2], [3,4]])
>>> a.flatten()
array([1, 2, 3, 4])
>>> a.flatten('F')
array([1, 3, 2, 4])

Source: Scipy.org

资料来源:Scipy.org