Home > Software design >  How to bind elements of the same index in numpy array in python
How to bind elements of the same index in numpy array in python

Time:12-03

I'm trying to make a function that bind the elements of the same index of two different subarrays in one numpy array. If the input is, for example, input = [[1,2,3],[4,5,6]], I want to have it output =[(1,4),(2,5),(3,6)] or something similar. The number of subarray can varry (input is *input) I would either sum the newly binded elements together at the end. For example, [1 4, 2 5, 3 6]. I know a work around but I would like to know if there are some built-in functions to do this.

What I've tried -numpy.add() function requires two numpy arrays so this won't work

  • for x,y in zip (*input[i] for i in len(lists)) gives an error of insufficient arguments

CodePudding user response:

If in the end you are interested in the sum of elements, I would simply do:

import numpy as np
input = np.array([[1,2,3],[4,5,6]])
np.sum(input, axis=0)

ouput = array([5, 7, 9])

If you do want to have the intermediate array at some point, you just need a transposition:

input.T

output = array([[1, 4], [2, 5], [3, 6]])

  • Related