0

I have and array like this :

[[[a, b], [c, d], [e, f]]]

When i shape to this array it gives (2,)

I tried reshape(-1) method but i did not work. I want to reshape this array into:

[[a, b], [c, d], [e, f]]

How can i convert that? I would be glad if you help.

5
  • Is this a list or a numpy array ? It would also help if you provide the initial shape of your array. Commented Dec 11, 2019 at 12:53
  • @IbrahimSherifYahia it is numpy.ndarray Commented Dec 11, 2019 at 13:03
  • What are a, b, etc. As @uniQ shows, if they are single characters (or numbers) , the result is an array with shape (1,3,2), not the (2,) that you claim. If it really was (1,3,2) shape, you could just index on the first dimension and get a (3,2) array. That indexing would work even if it was a nested list instead of array. Commented Dec 11, 2019 at 17:04
  • You say reshape(-1) doesn't work. "doesn't work" is not very informative - to you or us. What was wrong? An error message? A wrong result? Don't just throw that result away; try to learn from it. Commented Dec 11, 2019 at 17:08
  • I'm gonna do next time. Thank you! @hpaulj Commented Dec 12, 2019 at 5:17

3 Answers 3

3

You can use the numpy.squeeze function.

a = np.array([[["a", "b"], ["c", "d"], ["e", "f"]]])
print(a.shape)
print(a)

Output:

(1, 3, 2)
[[['a' 'b']
  ['c' 'd']
  ['e' 'f']]]
b = a.squeeze(0)
print(b.shape)
print(b)

Output:

(3, 2)
[['a' 'b']
 ['c' 'd']
 ['e' 'f']]
Sign up to request clarification or add additional context in comments.

1 Comment

I tried this but it gives me now [([[a, b], [c, d], [e, f]])]. And it gives to me ValueError: too many values to unpack (expected 2)
0
chars_list = [[["a", "b"], ["c", "d"], ["e", "f"]]]
chars_list_one = []
for element in chars_list:
    for element_one in element:
        chars_list_one.append(element_one)
print(chars_list_one)

Comments

0

You can use the .squeeze method.

import numpy as np

a = np.array([[['a', 'b'], ['c', 'd'], ['e', 'f']]])
a.squeeze()

Output:

array([['a', 'b'],
       ['c', 'd'],
       ['e', 'f']], dtype='<U1')

1 Comment

I tried this but it gives me now [([[a, b], [c, d], [e, f]])]. And it gives to me ValueError: too many values to unpack (expected 2)

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.