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.
CodePudding user response:
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']
CodePudding user response:
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()}')