1

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.

1
  • 1
    Wouldn't it be easier if you worked with dataframes where these are actual keys and values? Then you can add the corresponding rows of the two df's. Commented May 12, 2021 at 22:25

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

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.