Coder1
Coder1

Reputation: 13321

Sum 2 arrays based on indices defined in separate arrays

I'm using Numpy and Pandas to generate a series of prices in .25 increments before creating another array of associated values from a dataframe.

I end up with an array of keys, and an array of values.

What is the best way to sum two sets of these key/value array pairs on their respective prices?

keys1 = np.array([1.0, 1.25, 1.5, 1.75])
vals1 = np.array([1, 1, 1, 1])

keys2 = np.array([1.25, 1.5])
vals2 = np.array([1, 1])

Desired result:

(1, 2, 2, 1)

Note: I'm not concerned with cases where the 2nd set has values that do not exist in the first set. Just looking for a clean way to add the 2nd set of values to the 1st set of values.

Upvotes: 1

Views: 29

Answers (1)

j-i-l
j-i-l

Reputation: 10957

You can use numpy's searchsorted for this. This works just fine in your case as searchsorted returns the

indices where elements should be inserted to maintain order

which are exactly the indices in vals1 where the values of vals2 should be added to.

So basically:

vals1[np.searchsorted(keys1, keys2)] += vals2

But keep in mind that this only works if both, keys1 and keys2, are sorted and if keys2 only holds elements that are also present in keys1.

Upvotes: 2

Related Questions