0

I am not very familiar with python so I apologise in advance. Is it at all possible to have a numpy array such as numpy.array([a, b, c]) and add that array to an empty numpy array as an element?

Assuming this is possible, is it possible to then sum the first value of each element of multiple arrays within the main numpy array. For instance,

numpy.array([numpy.array([a,b,c]), numpy.array([d,e,f])])

to then become

numpy.array([a + d, b + e, c + f])

I hope I have managed to explain clearly if unsure please feel free to ask me to expand.

Many Thanks :-)

4
  • 3
    Fire up your python interpreter and try it out. Commented Feb 28, 2018 at 21:45
  • There is an object dtype that allows arrays to contain 'anything', much as lists do. But creating such an array can be tricky. np.array tries, if possible, to create a multidimensional array of numbers. If falls back on the object dtype if it can't - or it raises an error. We get lots of SO questions from people who don't understand these complexities, e.g. stackoverflow.com/questions/49032948/… Commented Feb 28, 2018 at 22:02
  • read numpy tutorials. nd array refers to n-dimensional arrays. 3D array could include multiple 2D arrays etc. Commented Feb 28, 2018 at 22:48
  • Do you really need arrays within an array? How about a 2d array instead? np.array([[1,2,3],[4,5,6]]). Or just adding 2 arrays together? np.array([1,2,3])+np.array([4,5,6])`. Commented Feb 28, 2018 at 23:59

2 Answers 2

0

2 1d arrays:

In [79]: x1=np.array([1,2,3])
In [80]: x2=np.array([4,5,6])

Make new array - 2d, with 2 rows

In [81]: x12 = np.array((x1,x2))
In [82]: x12
Out[82]: 
array([[1, 2, 3],
       [4, 5, 6]])

np.array([[1,2,3],[4,5,6]]) does the same thing.

The arrays can be summed, element by element:

In [83]: x1 + x2
Out[83]: array([5, 7, 9])

rows of the 2d array can also be summed:

In [84]: x12.sum(axis=0)
Out[84]: array([5, 7, 9])
Sign up to request clarification or add additional context in comments.

Comments

0

Arrays of arrays are essentially what matrices are, so I'd just make an n-dimensional numpy array. That way you can sum element-wise in a given direction.

import numpy as np
x = np.array([[1, 2, 3], [4, 5, 6]], np.int32) # 2x3 matrix

Normally you would want to loop through indices but for your example it makes more sense to do the summations individually :)

a_plus_d = sum(x[:,0]) # sum first column
b_plus_e = sum(x[:,1]) # sum second column
c_plus_f = sum(x[:,2]) # sum third column

1 Comment

Ah that makes complete sense! Life saver, thank you very much! :-)

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.