展平 NumPy 数组列表? [英] Flattening a list of NumPy arrays?
问题描述
看来我有 NumPy 数组列表格式的数据 (type() = np.ndarray
):
It appears that I have data in the format of a list of NumPy arrays (type() = np.ndarray
):
[array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]),
array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]),
array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]),
array([[ 0.00353654]]), array([[ 0.00353654]]), array([[ 0.00353654]]),
array([[ 0.00353654]])]
我正在尝试将其放入 polyfit 函数中:
I am trying to put this into a polyfit function:
m1 = np.polyfit(x, y, deg=2)
然而,它返回错误:TypeError: expected 1D vector for x
我假设我需要将我的数据展平成类似的东西:
I assume I need to flatten my data into something like:
[0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654 ...]
我尝试了一个列表理解,它通常适用于列表列表,但正如预期的那样没有奏效:
I have tried a list comprehension which usually works on lists of lists, but this as expected has not worked:
[val for sublist in risks for val in sublist]
最好的方法是什么?
推荐答案
你可以使用 numpy.concatenate
,顾名思义,基本上将这样一个输入列表的所有元素连接成一个单一的 NumPy 数组,就像这样 -
You could use numpy.concatenate
, which as the name suggests, basically concatenates all the elements of such an input list into a single NumPy array, like so -
import numpy as np
out = np.concatenate(input_list).ravel()
如果你希望最终输出是一个列表,你可以像这样扩展解决方案 -
If you wish the final output to be a list, you can extend the solution, like so -
out = np.concatenate(input_list).ravel().tolist()
样品运行 -
In [24]: input_list
Out[24]:
[array([[ 0.00353654]]),
array([[ 0.00353654]]),
array([[ 0.00353654]]),
array([[ 0.00353654]]),
array([[ 0.00353654]]),
array([[ 0.00353654]]),
array([[ 0.00353654]]),
array([[ 0.00353654]]),
array([[ 0.00353654]]),
array([[ 0.00353654]]),
array([[ 0.00353654]]),
array([[ 0.00353654]]),
array([[ 0.00353654]])]
In [25]: np.concatenate(input_list).ravel()
Out[25]:
array([ 0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654,
0.00353654, 0.00353654, 0.00353654, 0.00353654, 0.00353654,
0.00353654, 0.00353654, 0.00353654])
转换为列表 -
In [26]: np.concatenate(input_list).ravel().tolist()
Out[26]:
[0.00353654,
0.00353654,
0.00353654,
0.00353654,
0.00353654,
0.00353654,
0.00353654,
0.00353654,
0.00353654,
0.00353654,
0.00353654,
0.00353654,
0.00353654]
这篇关于展平 NumPy 数组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!