Skip to content
Advertisement

Getting a single array containing several sub-arrays iteratively

I have a little question about python Numpy. What I want to do is the following:

having two numpy arrays arr1 = [1,2,3] and arr2 = [3,4,5] I would like to obtain a new array arr3 = [[1,2,3],[3,4,5]], but in an iterative way. For a single instance, this is just obtained by typing arr3 = np.array([arr1,arr2]).

What I have instead, are several arrays e.g. [4,3,1 ..], [4,3,5, ...],[1,2,1,...] and I would like to end up with [[4,3,1 ..], [4,3,5, ...],[1,2,1,...]], potentally using a for loop. How should I do this?

EDIT:

Ok I’m trying to add more details to the overall problem. First, I have a list of strings list_strings=['A', 'B','C', 'D', ...]. I’m using a specific method to obtain informative numbers out of a single string, so for example I have method(list_strings[0]) = [1,2,3,...], and I can do this for each single string I have in the initial list.

What I would like to come up with is an iterative for loop to end up having all the numbers extracted from each string in turn in the way I’ve described at the beginning, i.e.a single array with all the numeric sub-arrays with information extracted from each string. Hope this makes more sense now, and sorry If I haven’t explained correctly, I’m really new in programming and trying to figure out stuff.

Advertisement

Answer

Well if your strings are in a list, we want to put the arrays that result from calling method in a list as well. Python’s list comprehension is a great way to achieve that.

list_strings = ['A', ...]

list_of_converted_strings = [method(item) for item in list_strings]

arr = np.array(list_of_converted_strings)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement