I am in a position to extract whole data from an array. The simplest method would be simply passing array[:]
. However, I want to make it automated as part of the larger project where the index would be varying with the data format. Therefore, is it possible to extract the whole data by passing a slicing string ":" as an index to the array?
To make things clear, here is an example of what I am trying to do.
create an array:
>>> import numpy as np
>>> a = np.random.randint(0,10,(5,5))
>>> a
array([[3, 3, 3, 7, 2],
[8, 6, 8, 6, 3],
[4, 2, 2, 0, 3],
[4, 0, 6, 0, 1],
[1, 2, 0, 2, 8]])
General slicing of dataset using tradition method:
>>> a[:]
array([[3, 3, 3, 7, 2],
[8, 6, 8, 6, 3],
[4, 2, 2, 0, 3],
[4, 0, 6, 0, 1],
[1, 2, 0, 2, 8]])
It works. However, I intend to make :
as a variable and try to extract with above example like below:
>>> b = ":"
>>> a[b]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
As per the printed error, I did some correction while defining variable as indicated below which also resulted in error:
>>> c = slice(':')
>>> a[c]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: slice indices must be integers or None or have an __index__ method
So, is it possible at all to extract data by passing a slicing string ":" as an index to an array?
Update
Thank you all for your comments. It is possible with following method:
>>> c = np.index_exp[:]
>>> a[c]
array([[3, 3, 3, 7, 2],
[8, 6, 8, 6, 3],
[4, 2, 2, 0, 3],
[4, 0, 6, 0, 1],
[1, 2, 0, 2, 8]])