0

Apologies if this question has an elementary answer, but I have not been able to find one yet.

I have some data that was originally a numpy array of shape (N, M), but where certain columns have then been removed. For illustration lets say M=6 and 2 columns where removed, leaving a (N, 4) array. What I also have is an array denoting whether a column was kept or not with a Boolean value (True if kept, False if not), e.g. array([False, True, True, False, True, True]).

What I would like to do would be to reconstruct an (N, 6) array from the (N, 4) array and the boolean markers, with the columns reintroduced at the right index (filled with zeros).

Any help on the requisite slicing etc approaches would be valued!

1
  • 1
    You should be able to make a new array with np.insert, using [0, 3], insert positions as an argument. But read its docs. But it isn't hard to create a new array directly. Commented Oct 18, 2020 at 23:54

1 Answer 1

2

Let's try this:

# original array -- for references only
arr = np.arange(12).reshape(-1,6)

# keep indexes
keep = np.array([False,  True,  True,  False,  True,  True])

# array after removing the columns
removed_arr = arr[:,keep]

# output array
out = np.zeros((removed_arr.shape[0], len(keep)), dtype=removed_arr.dtype)

# copy the values of `removed_arr` to output
out[:, keep] = removed_arr

Output:

array([[ 0,  1,  2,  0,  4,  5],
       [ 0,  7,  8,  0, 10, 11]])
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.