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

cs95
406k106 gold badges744 silver badges793 bronze badges
asked Jun 21, 2019 at 14:54
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.

answered Jun 21, 2019 at 14:57
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]
answered Jun 21, 2019 at 15:11

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

answered Jun 21, 2019 at 16:13

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]
answered Jun 21, 2019 at 15:02

1 Comment

1.0 requested to be 1

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.