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
  • 379,657
  • 97
  • 704
  • 746
  • Possible duplicate of [Converting NumPy array into Python List structure?](https://stackoverflow.com/questions/1966207/converting-numpy-array-into-python-list-structure) – BenT Jun 21 '19 at 17:46

4 Answers4

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.

  • _"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`. – Paul Panzer Jun 21 '19 at 15:13
  • @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. – Gilles-Philippe Paillé Jun 21 '19 at 15:20
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]
Alexandre B.
  • 5,387
  • 2
  • 17
  • 40
1

very simple:

[ls[0] for ls in arr]

I Hope this helps

smerllo
  • 3,117
  • 1
  • 22
  • 37
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]
Rudolf Fanchini
  • 103
  • 1
  • 7