0

I need to convert numpy array in to a list

[ [1.        ] [0.89361702] [0.4893617 ] [0.44680851] [0.0212766 ] [0.        ] ]

this to

[ 1 ,0.89361702, 0.4893617,  0.44680851 ,0.0212766 ,0]

But when i use

duration= du.tolist()

duration looks like this

[[1.0],
[0.8936170212765937],
[0.4893617021276597],
[0.4468085106382951],
[0.02127659574468055],
[0.0]]

Please ignore the numbe of decimal points

1

4 Answers 4

3

Use du.reshape(-1).tolist(). reshape(-1) returns a view (whenever possible) of the flattened array, so it minimizes the overhead as compared to flatten that creates a copy.

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

2 Comments

"ravel returns a view (whenever possible) ..." Not true. For example: x = np.eye(4).T[0] np.shares_memory(x,x.ravel()) returns False whereas np.shares_memory(x,x.reshape(-1)) returns True.
@PaulPanzer It is does it whenever it can, but unfortunately, in your case, it doesn't. From the ravel documentation, it mentions "When a view is desired in as many cases as possible, arr.reshape(-1) may be preferable.". Thanks for your comment, I will edit my answer.
2

Surprised nobody suggested the flatten method from numpy (doc). It's mostly the same as the ravel method suggested by @Gilles-Philippe Paillé.

One example:

import numpy as np

data = [[1.0],
        [0.89361702],
        [0.4893617],
        [0.44680851],
        [0.0212766],
        [0.0],]
array = np.array(data, dtype=float)

my_list= array.flatten().tolist()

print(my_list)
# [1.0, 0.89361702, 0.4893617, 0.44680851, 0.0212766, 0.0]

1 Comment

flatten is like ravel except it always makes a copy.
1

very simple:

[ls[0] for ls in arr]

I Hope this helps

Comments

0

I did it this way.

dura = [[1.0],
[0.8936170212765937],
[0.4893617021276597],
[0.4468085106382951],
[0.02127659574468055],
[0.0]]
new = []
for x in dura:
    if len(x)== 1:
        new.append(x[0])

and got this when printing new

[1.0, 0.8936170212765937, 0.4893617021276597, 0.4468085106382951, 0.02127659574468055, 0.0]

1 Comment

1.0 requested to be 1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.