0

I have the following example array with strings:

 ['100000000' '101010100' '110101010' '111111110']

I would like to be able to remove some elements by index in each of the strings in the array simultaneously. For example if I will remove elements with index 6 and 8, I should receive the following outcome:

 ['1000000' '1010110' '1101000' '1111110']

All my attempts failed so far maybe because the string is immutable, but am not sure whether I have to convert and if so - to what and how.

1
  • 1
    You have to use string slicing and assign the results back to the array elements. Commented Feb 2, 2023 at 0:02

2 Answers 2

3
import numpy as np

a = np.array(['100000000', '101010100', '110101010', '111111110'])

list(map(lambda s: "".join([c for i, c in enumerate(str(s)) if i not in {5, 7}]), a))

Returns:

['1000000', '1010110', '1101000', '1111110']
Sign up to request clarification or add additional context in comments.

4 Comments

Iterating over a list is faster than iterating over a numpy array: Just mapping a.tolist() instead of a reduces runtime (~30% for this array) to 5.36 µs ± 52.3 ns per loop from 7.52 µs ± 170 ns
It provides the same outcome as in the examples, but I am trying to point elements to be removed by index. In this case why we are putting 5 and 7 instead of 7 and 8?
Python lists start with index 0, so if you want to remove 6th and 8th, that's indexes 5 and 7. If this doesn't solve your whole problem, try to describe what you imagine the final output should be. This example gives the output you indicated.
It can also take this syntax - list(map(lambda s: "".join(c for i, c in enumerate(str(s), 1) if i not in {6, 8}), a)) Note: skip []
2

Another way to do this is to convert a into a 2D array of single characters, mask out the values you don't want, and then convert back into a 1D array of strings.

import numpy as np

a = np.array(['100000000', '101010100', '110101010', '111111110'])

b = a.view('U1').reshape(*a.shape, -1)

mask = np.ones(b.shape[-1], dtype=bool)
mask[[5, 7],] = False

b = b[:, mask].reshape(-1).view(f'U{b.shape[-1] - (~mask).sum()}')

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.