I am trying to plot a dataset using matplotlib
which contains multiple y
coordinates per x
. To plot them I have to combine these arrays to show them in a single plot. How do I zip each element from a 1D array with the elements from each row of a 2D array (corresponding with the index for the element of the 1D array)? Without using explicit for-loops. Using built-ins (eg. zip/list comprehension) or even better: numpy
?
Turning:
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)]
I thought of following:
Extend x
to be of same size as y
Flatten y
Zip x
and y
as follows
>>> 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)]
I would love to learn how more efficiently this can be done.
Please comment or answer more efficient approach.
x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]
result = [(i[0], i[1][0]) for i in zip(x,y)] + [(i[0], i[1][1]) for i in zip(x,y)]
[(1, 4), (2, 6), (3, 8), (1, 5), (2, 7), (3, 9)]
Inspired by approach 5 here :
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)
Gives
[(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]
A variation on your repeat
and reshape
approach:
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]])
It's using broadcasting
to map the x
and y
onto the res
array.
This is making use of iterators only, using itertools.chain.from_iterable
import itertools
x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]
list(zip(list(itertools.chain.from_iterable(itertools.repeat(n, 2) for n in x)),
list(itertools.chain.from_iterable(y))))
Output
[(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]
This should be faster in longer runs, IMHO.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.