Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Slicing using vectors
#5
(Nov-16-2019, 12:00 AM)micseydel Wrote: It's generally helpful if you post runnable code (yours lacks at least one import) and the full, verbatim error message (ideally in error tags). Here's what I get when I run your code after adding the import:
Error:
Traceback (most recent call last): File "doit.py", line 10, in <module> extract3_A = A[i:j,:] # fails TypeError: only integer scalar arrays can be converted to a scalar index

The code has been added as it stands to highlight the issue I got.

Finally I found a way that answers to my need without using any loop but the Kronecker product; it has been checked on a small size matrix, but it quite interesting with million of lines (tested with 10 million on my old laptop).

Paul
import time
import numpy as np

#n = 1_000_000
n = 10
m = 2
A = np.array(np.random.randint(66, size=(n,m), dtype=np.int32))
i = np.array(np.random.randint(n-4, size=int(0.5*n), dtype=np.int32))
j = i + 4*np.ones(int(0.5*n), dtype=np.int32)

## the i vector gives us the first index of values we want to get from A
## in the current case we want to get values from i to (i+4)
## with only 1 index, slicing is traditionnally used as A[100:104,4] for example

## the "trick" or the solution I've been using is to specify each index I want to extract
## using the Kronecker product as follow:
t0 = time.time()
k1 = np.arange(4, dtype=np.int32)
k2 = np.ones(int(0.5*n), dtype=np.int32)
k3 = np.ones(4, dtype=np.int32)
kron1 = np.kron(k2,k1)  # here [0 1 2 3] is repeated (0.5*n) times => from j vector
kron2 = np.kron(i,k3)   # here each index is repeated (0.5*n) times => from i vector
index = kron1 + kron2   # then each index varies from its initial value to (initial+4)
Extract_A = np.copy(A[index,:]) # all the indexes have been explicitly expressed and we can extract the values as usually
t1 = time.time()
print("The new solution took {} seconds".format(t1-t0))
Reply


Messages In This Thread
Slicing using vectors - by paul18fr - Nov-14-2019, 10:06 AM
RE: Slicing using vectors - by schuler - Nov-15-2019, 12:15 AM
RE: Slicing using vectors - by paul18fr - Nov-15-2019, 11:00 AM
RE: Slicing using vectors - by micseydel - Nov-16-2019, 12:00 AM
RE: Slicing using vectors - by paul18fr - Nov-16-2019, 10:43 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Scaling of mapped vectors? sricha1217 1 2,367 Apr-10-2018, 10:26 AM
Last Post: sricha1217
  Statistics: Two histograms based on word frequency vectors fancy_panther 2 4,756 Mar-27-2017, 01:18 AM
Last Post: zivoni

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020