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
-
Possible duplicate of Converting NumPy array into Python List structure?BenT– BenT2019年06月21日 17:46:04 +00:00Commented Jun 21, 2019 at 17:46
4 Answers 4
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
Paul Panzer
"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
.Gilles-Philippe Paillé
@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.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
hpaulj
flatten
is like ravel
except it always makes a copy.very simple:
[ls[0] for ls in arr]
I Hope this helps
answered Jun 21, 2019 at 16:13
Comments
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
Tomerikoo
1.0
requested to be 1
lang-py