0

Hi I have two arrays as below.

1) An array made up of 1 and 0. 1 Signifies that its an active day and 0 is a holiday.

2) An arithmetic sequence which is smaller in length compared to array 1.

The result array needs to be a combination of 1) & 2) wherein the arithmetic sequence needs to follow the positions of 1s. In other words the array 2 needs to expanded to array 1 length with 0s inserted in the same position as array 1.

One way i could solve this is using numpy.insert with slice. However, since the lengths are different and the array 1 is dynamic i need an efficient way to achieve this.

Thanks

Final result

3 Answers 3

1

An alternative one-liner solution

Setup

binary = np.array([1, 1, 0, 1, 0, 1, 1, 0, 1, 0])
arithmetic = np.arange(1, 7)

Solution

#find 1s from binary and set values from arithmetic
binary[np.where(binary>0)] = arithmetic

Out[400]: array([1, 2, 0, 3, 0, 4, 5, 0, 6, 0])
Sign up to request clarification or add additional context in comments.

Comments

1

Create the result array of the right length (len(binary)) filled with 0s, then use the binary array as a mask to assign into the result array. Make sure the binary mask is of the bool dtype.

>>> binary = np.array([1, 1, 0, 1, 0, 1, 1, 0, 1, 0], dtype=bool)
>>> arithmetic = np.arange(1, 7)
>>> result = np.zeros(len(binary), dtype=arithmetic.dtype)
>>> result[binary] = arithmetic
>>> result
array([1, 2, 0, 3, 0, 4, 5, 0, 6, 0])

Comments

0

Another way would be to create a copy of binary array and replace all non-zero values by arithmatic array

seq = np.arange(1, len(bi_arr[bi_arr != 0])+1)

final_result = bi_arr.copy()

final_result[final_result != 0] = seq

print(final_result)

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

The bi-arr remains unchanged

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.