我试图用matplotlib绘制一个数据集,该数据集包含每个x的多个y坐标。要绘制它们,我必须将这些数组组合起来,在一个图中显示它们。如何使用2D数组的每行元素(对应于一维数组元素的索引)从一维数组中压缩每个元素?而不用显式的for-循环。使用内置的(如。)或者更好的理解:numpy
车削:
x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]Into:
r = [(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]发布于 2020-02-14 18:05:22
我想到了以下几点:
x扩展为与y大小相同的yx和y如下所示
>>> x = [1, 2, 3]
>>> y = [[4, 5], [6, 7], [8, 9]]
>>> x = np.array(x).repeat(2)
>>> y = np.array(y).reshape(-1)
>>> list(zip(x, y))
[(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]我想知道如何更有效地做到这一点。
请评论或回答更有效的方法。
发布于 2020-02-14 18:18:55
受方法5( 这里 )启发
from functools import reduce
x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]
def listOfTuples(l1, l2):
l = list(map(lambda x, y:[(x,y[0]), (x,y[1])], l1, l2))
m = reduce(lambda x, y: x + y, l)
return(m)
r = listOfTuples(x, y)给出
[(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]发布于 2020-02-14 18:21:14
您的repeat和reshape方法的一个变体:
In [89]: x = [1, 2, 3]
...: y = [[4, 5], [6, 7], [8, 9]]
In [90]: res = np.zeros((3,2,2),int)
In [91]: res[:,:,1]=y
In [92]: res[:,:,0]=np.array(x)[:,None]
In [93]: res
Out[93]:
array([[[1, 4],
[1, 5]],
[[2, 6],
[2, 7]],
[[3, 8],
[3, 9]]])
In [94]: res.reshape(6,2)
Out[94]:
array([[1, 4],
[1, 5],
[2, 6],
[2, 7],
[3, 8],
[3, 9]])它使用broadcasting将x和y映射到res数组。
https://stackoverflow.com/questions/60231266
复制相似问题