0

I have a 2D array in a format of (image, ID) , where some images have the same ID. For example:

data_2d = [(image1, 1) , (image2, 2),(image3, 2) , image(4, 2) , (image5,3), (image6,3)]

Now my goal is to convert this to a 3D array using their id numbers. To be more clear:

data_3d = [[(image1, 1) ] , [(image2, 2),(image3, 2) , image(4, 2)] , [(image5,3), (image6,3)]]  

Is there a way to this?

1 Answer 1

1

Use a dictionary (or a defaultdict) to group the tuples by id, and then convert the dictionary's values to a list:

from collections import defaultdict

data_2d = [('image1', 1), ('image2', 2), ('image3', 2), ('image4', 2), ('image5', 3), ('image6', 3)]

groups = defaultdict(list)
for e in data_2d:
    groups[e[1]].append(e)

data_3d = list(groups.values())
print(data_3d)

Output

[[('image1', 1)], [('image2', 2), ('image3', 2), ('image4', 2)], [('image5', 3), ('image6', 3)]]

Note that I change your variable names to strings to make the code runable.

Sign up to request clarification or add additional context in comments.

3 Comments

This code does the job, I get an array with the shape of (213,). Meaning I have 213 IDs, and when I want to get the shape of each IDs using for i in data_3d: print(i.shape), I get the following error: 'list' object has no attribute 'shape'. However, when I use for i in data_3d: print(i[0].shape) I get the shape of each image, for example (541, 720, 3) , etc. how can i fix this?
Each element of data_3d is a list, so it doesn't have a shape. What exactly are you trying to fix?
Sorry, I found my mistake. it was a typo. You're answer completely fixed my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.