I have a list in python and I want to convert it to an array to be able to use ravel()
function.
-
2Please, try to answer requests for clarifications and improve your questions instead of spawning lots of not-really-good questions. Finally, read carefully this answer. I think it solves your big problem... – jorgeca Apr 7 '13 at 22:30
Use numpy.asarray
:
import numpy as np
myarray = np.asarray(mylist)
-
25
-
11well, asarray it's safer as it won't copy arrays but simply return them, so it's a good habit to use it unless one it's sure to wawnt a copy of the original data – EnricoGiampieri Apr 7 '13 at 22:25
-
1@EnricoGiampieri, fair, but wouldn't you need to get an array out of this no matter what? I guess I don't follow how you wouldn't get either command to generate a new array object. – fgb Apr 7 '13 at 22:29
-
both command will create a new array starting from a list, that's for sure, but often the point is to convert an input to a specific format to apply certain method, and this looks more like the case of the OP. using asarray is a good habit unless one is certain that a new copy is needed. simply typing
array
is enough, but why let slip the possibility to educate the OP to some good habit while we are here? – EnricoGiampieri Apr 9 '13 at 14:41 -
I just wanted to say that @fgb proposed an adequate solution. the '.asarray' function returns a numpy object whereas '.array returns you an array directly. Anyways, thanks to both of you guys! – Adrian Grzywaczewski Mar 10 '18 at 18:14
create an int array and a list
from array import array
listA = list(range(0,50))
for item in listA:
print(item)
arrayA = array("i", listA)
for item in arrayA:
print(item)
I wanted a way to do this without using an extra module. First turn list to string, then append to an array:
dataset_list = ''.join(input_list)
dataset_array = []
for item in dataset_list.split(';'): # comma, or other
dataset_array.append(item)
-
Not possible to edit a typo: the first row should be
dataset_list = ';'.join(input_list)
– Alex Poca May 28 '20 at 11:18
If all you want is calling ravel
on your (nested, I s'pose?) list, you can do that directly, numpy
will do the casting for you:
L = [[1,None,3],["The", "quick", object]]
np.ravel(L)
# array([1, None, 3, 'The', 'quick', <class 'object'>], dtype=object)
Also worth mentioning that you needn't go through numpy
at all.
Use the following code:
import numpy as np
myArray=np.array([1,2,4]) #func used to convert [1,2,3] list into an array
print(myArray)
if variable b has a list then you can simply do the below:
create a new variable "a" as: a=[]
then assign the list to "a" as: a=b
now "a" has all the components of list "b" in array.
so you have successfully converted list to array.
-
8Actually, no ... this is completely wrong. All you'll have is two variables pointing at the same list, not a numpy array. – Ajean Nov 25 '15 at 22:05