Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting parts of array repeatedly

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]
like image 904
Melron Avatar asked Apr 29 '19 09:04

Melron


People also ask

How do you repeat an element in an array?

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.

How do I extract an array from an 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.


2 Answers

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'])
like image 188
Sheldore Avatar answered Oct 17 '22 12:10

Sheldore


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']
like image 1
jdehesa Avatar answered Oct 17 '22 12:10

jdehesa