0

I have an array with (n,) dimension and for a project I need to have this array with (n,3) shape. This array is a set of a 3-dimensional points.

This is the code :

vertices =  np.array([line[7:] for line in content if line.startswith('vertex')]) #7 parce que 7 char dans 'vertex '
vertices = np.reshape(vertices,(vertices.size,3))

This is the error :

cannot reshape array of size 13716 into shape (13716,3)

How can I reshape the array above?

2
  • 2
    What you currently do is creating an array of strings, what you probably actually want to do is extracting numbers from the strings. In other words: the step that converts each string of numbers into the actual number is missing. Now, depending of what the lines in content actually look like, the approach to achieve this could vary. Could you provide an excerpt of content to see what your data looks like?
    – simon
    Commented May 16 at 10:46
  • reshape cannot change the total number of elements of an array. You can reshape to (n,1), e.g with vertices[:,None]. Due to broadcasting rules that may be enough. To get (n,3) shape, you'll need to use np.repeat.
    – hpaulj
    Commented May 16 at 17:20

1 Answer 1

2

I am not clear about it can help you, because I don't understand very well your question, maybe I need more info. However, if each vertex have 3 coords or numbers like I write in the example, here is a solution.

# Import the dependencies
import numpy as np

# Assuming content is some like that, each vertex have three dimensions
content = [
    'vertex 1.0 2.0 3.0',
    'vertex 4.0 5.0 6.0',
    'vertex 9 10 11'
]

# Extract the coordinates of the vertices
# Split each line, take elements after 'vertex', convert to float, and create a NumPy array
vertices = np.array([line.split()[1:] for line in content if line.startswith('vertex')], dtype=float)

# Verify if the size of the array is a multiple of 3
# Reshape the array to convert it to shape (n, 3)
vertices = vertices.reshape((-1, 3))

# Print the reshaped array
print(vertices)

If this doesn't is the situation, 13746/3 = 4582. So, you can do the following:

vertices = np.reshape(vertices,(-1, 3))

NumPy calculate the necessary rows to reshape with 3 columns/dimensions.

About your question, I think that is impossible to reshape (n,) to (n,3), unless do you want to repeat the entries?

Not the answer you're looking for? Browse other questions tagged or ask your own question.