1

I have created a code in which from my lists I create an array, which must be vertical, like a vector, the problem is that using the reshape method I don't get anything.

import numpy as np

data = [[ 28,    29,    30,    19,    20,    21],
        [ 31,    32,    33,    22,    23,      24],
        [  1,    34,    35,    36,    25,    26],
        [  2,    19,    20,    21,    10,    11],
        [  3,     4,     5,     6,     7,    8 ]]

index = []
for i in range(len(data)):
    index.append([data[i][0], data[i][1], data[i][2],
                    data[i][3], data[i][4], data[i][5]])   
    y = np.array([index[i]])
#    y.reshape(6,1)

Is there any solution for these cases? Thank you.

I'm looking for something like this to remain:

enter image description here

2 Answers 2

1

If you want to view each row as a column, transpose the array in any one of the following ways:

index = data.T
index = np.transpose(data)
index = data.transpose()
index = np.swapaxes(data, 0, 1)
index = np.moveaxis(data, 1, 0)
...

Each column of index will be a row of data. If you just want to access one column at a time, you can do that too. For example, to get row 3 (4th row) of the original array, any of the following would work:

y = data[3, :]
y = data[3]
y = index[:, 3]

You can get a column vector from the result by explicitly reshaping it to one:

y = y.reshape(-1, 1)
y = np.reshape(y, (-1, 1))
y = np.expand_dims(y, 1)

Remember that reshaping creates a new array object which views the same data as the original. The only way I know to reshape an array in-place is to assign to its shape attribute:

y.shape = (y.size, 1)
Sign up to request clarification or add additional context in comments.

Comments

0

You can use flatten() from numpy https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html

(if you want a copy of the original array without modifying the original)

import numpy as np

data = [[ 28,    29,    30,    19,    20,    21],
        [ 31,    32,    33,    22,    23,      24],
        [  1,    34,    35,    36,    25,    26],
        [  2,    19,    20,    21,    10,    11],
        [  3,     4,     5,     6,     7,    8 ]]

data = np.array(data).flatten()

print(data.shape)
(30,)

You can also use ravel()

(if you don't want a copy)

data = np.array(data).ravel()

If your array always has 2-d, this also works,

data = data.reshape(-1)

1 Comment

Use ravel to avoid copying the data

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.