1

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.

3
  • 2
    How do you have "several arrays" if they're not already in another array? Commented Jun 11, 2021 at 16:16
  • yeah, on what, do you want to use loop if you don't have an array in the first place Commented Jun 11, 2021 at 16:19
  • I'm sorry for any lack, I've tried to add more details to the question Commented Jun 11, 2021 at 16:24

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

Numpy arrays are of fixed dimension i.e. for example a 2D numpy array of shape n X m will have n rows and m columns. If you want to convert a list of lists into a numpy array all the the sublists in the main list should be of same length. You cannot convert it into a numpy array if sublist are of varying size.

For example, below code will give an error

np.array([[1], [3,4]]])

so if all the sublist are of same size then you can use

np.array([method(x) for x in strings]])

Comments

Your Answer

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.