Olbert Daemmerer
Olbert Daemmerer

Reputation: 141

How to reshape/rearrange this list of numpy arrays

Problem:

How can I reshape/convert the following list of numpy arrays to the desired output? I would like to understand exactly how/why it works, so a step-by-step guide would much be appreciated, because I will have to work a lot with mixed numpy.array / list cases.

Minimal Example

import numpy as np

# create some dummy data
points1 = np.array([[1, 2, 3],[101, 102, 103]])
points2 = np.array([[4, 5, 6, 7, 8],[104, 105, 106, 107, 108]])
points3 = np.array([[9, 10, 11, 12],[109, 110, 111, 112]])

# gather data / this kind of list is what I will have to work with
points = [points1, points2, points3]

# what it looks like now
print(points)

# do some fance reshape/rearrange stuff
# new_points = ???

# desired output:
# new_points[0] = [1, 101]
# new_points[1] = [2, 102]
# new_points[2] = [3, 103]
# ...
# new_points[11] = [12, 112]

I only have access to points (not points1 etc.) and it will be a list of numpy arrays, that are all shaped (2, n). Are there any short, fancy indexing operations or would I have to go with a loop?

Upvotes: 0

Views: 329

Answers (2)

Espoir Murhabazi
Espoir Murhabazi

Reputation: 6386

check this simple solution :

new_points = np.concatenate([points1.T, points2.T, points3.T])

But if you don’t have access to point1, point2 , .. you can recast it as suggested in comments like this:

new_points = np.concatenate([x.T for x in points])

Upvotes: 0

Divakar
Divakar

Reputation: 221614

Given that they are a list of numpy arrays, that are all shaped (2, n), we can simply use one of the stacking functions.

So, with points = [points1, points2, points3], we would have few options to solve it.

np.hstack(points).T
np.concatenate(points,axis=1).T
np.column_stack(points).T

Or as @Mad Physicist suggested with np.c_ -

np.c_[tuple(points)].T

Upvotes: 2

Related Questions