Issue
I'm trying to transpose a jagged 2D array called "seats."
seats = np.array([
[1, 2, 3, 4, 5],
[1, 2, 3, 4],
[1, 2, 3],
[1, 2, 3, 4,],
[1, 2],
[1, 2]
], dtype = object)
I want to turn "seats" into an array looking like this:
transposed_seats = np.array([1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4], [5]
)
Is this possible?
I've tried the transpose function of numpy and zip, but none of that seems to work.
Solution
You can use itertools zip_longest.
import numpy as np
from itertools import zip_longest
seats = np.array([
[1, 2, 3, 4, 5],
[1, 2, 3, 4],
[1, 2, 3],
[1, 2, 3, 4],
[1, 2],
[1, 2]
], dtype=object)
directly, use zip_longest
list(zip_longest(*seats))
#[(1, 1, 1, 1, 1, 1), (2, 2, 2, 2, 2, 2), (3, 3, 3, 3, None, None), (4, 4, None, 4, None, None), (5, None, None, None, None, None)]
Now, if you do not want None
in your output then:
list([x for x in y if x is not None] for y in zip_longest(*seats))
#output
[[1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4], [5]]
Answered By - Goku - stands with Palestine
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.