I have an array:
[a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, etc]
How do I select every b and c without a for loop? Can I use slicing or anything else?
The resulting array should look like this:
[b1, c1, b2, c2, b3, c3, etc]
Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.
The extract() function imports variables into the local symbol table from an array. This function uses array keys as variable names and values as variable values. For each element it will create a variable in the current symbol table. This function returns the number of variables extracted on success.
You can use masking. Provided your input array has always a length in a multiple of 4, you can create a mask of pattern False, True, True, False
. I am taking an input of strings for example.
arr = np.array(['a1', 'b1', 'c1', 'd1', 'a2', 'b2', 'c2', 'd2', 'a3', 'b3', 'c3', 'd3'], dtype='str')
mask = [False, True, True, False]*int(len(arr)/4)
print (arr[mask])
# array(['b1', 'c1', 'b2', 'c2', 'b3', 'c3'])
You can select the data you want with numpy.lib.stride_tricks.as_strided
:
import numpy as np
from numpy.lib.stride_tricks import as_strided
data = np.array(['a0', 'b0', 'c0', 'd0', 'a1', 'b1', 'c1', 'd1', 'a2', 'b2', 'c2', 'd2'])
s = data.strides[0]
# No data is copied
data2 = as_strided(data[1:], shape=(data.size // 4, 2), strides=(4 * s, s), writeable=False)
print(data2)
# [['b0' 'c0']
# ['b1' 'c1']
# ['b2' 'c2']]
data3 = data2.ravel() # This causes a copy
print(data3)
#['b0' 'c0' 'b1' 'c1' 'b2' 'c2']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With