Understanding List to np.array Conversion

Asked 2 years ago, Updated 2 years ago, 120 views

I have a question about converting a list consisting of numpy.array to numpy.array.

Below is the matrix (test).

test= 
[array([4.76175243, 5.35280132, 5.6358859, 6.23928513, 6.75275935,
        6.82693267, 6.68472261, 5.93395087]),
 array([5.35280132, 5.6358859, 6.23928513, 6.75275935, 6.82693267,
        6.68472261, 5.93395087, 5.73621779]),
 array([5.6358859, 6.23928513, 6.75275935, 6.82693267, 6.68472261,
        5.93395087, 5.73621779, 5.22481018])]

I am expecting an array (3,8) of output.1 below by running np.array(test).
Output is .2(3,).
What is the cause?

Output.1

[4.76175243, 5.35280132, 5.6358859, 6.23928513, 6.75275935,
        6.82693267, 6.68472261, 5.93395087]),
 [5.35280132, 5.6358859 , 6.23928513, 6.75275935, 6.82693267,
        6.68472261, 5.93395087, 5.73621779]),
 [5.6358859 , 6.23928513, 6.75275935, 6.82693267, 6.68472261,
        5.93395087, 5.73621779, 5.22481018]])

Output.2

array([4.76175243, 5.35280132, 5.6358859, 6.23928513, 6.75275935,
       6.82693267, 6.68472261, 5.93395087]),
       array([5.35280132, 5.6358859, 6.23928513, 6.75275935, 6.82693267,
       6.68472261, 5.93395087, 5.73621779]),
       array([5.6358859, 6.23928513, 6.75275935, 6.82693267, 6.68472261,
       5.93395087, 5.73621779, 5.22481018]), dtype=object)

python python3 array numpy

2022-09-29 22:49

2 Answers

np.array is "converting raw Python list to NumPyarray", so converting "NumPyarray list" will result in "NumPyarray of NumPyarray".

If you want to convert a list of NumPyarrays to a two-dimensional NumPyarray, you can use np.stack.

>>> test = [np.array([1, 2, 3, 4],
...         np.array ([5, 6, 7, 8],
...         np.array ([9, 10, 11, 12])]
>>arr=np.stack(test)
>>arr
array([1,2,3,4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])


2022-09-29 22:49

I just started python, so I can't write anything accurate...

Output.1
In the first place, the parentheses () do not match.

"Also, looking at the definition code, the result may be an array of (3, 8), but since the format is a jug array, I think it is only natural that it should be ""output.2"", but what do you think?"

Note that the above example is an array of arrays.Therefore, it is slightly different from a simple two-dimensional array.


2022-09-29 22:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.