I am trying to access the first two letters of each index in a numpy array in python: I have read previous forum of the error “‘int’ object is not subscriptable , I know it;s not a string, but for my work it’s better to be numpy.array or if anyone suggest me with another thing, please help,
Here is my code:
JavaScript
x
19
19
1
import numpy as np
2
import os
3
import os.path
4
with open('trial.dat', 'r') as f:
5
data = f.readlines()
6
data = [(d+' ')[:d.find('#')].rstrip() for d in data]
7
8
x=len(data[0])
9
x_1=eval(data[0])
10
y=np.concatenate(x_1)
11
print(type(y))
12
for i in range (x):
13
if y[i[:2]]=='IS': # expected to be IS andso on.depened on the index
14
print('ok-CHOICE ONE ')
15
elif y[i[:2]]=='AT':
16
print('NOTok ')
17
else:
18
print()
19
Data to be used in the .dat file:
JavaScript
1
2
1
[["IS-2","AT-3","IS-4"]] # TYPE OF GN
2
Advertisement
Answer
You can’t efficiently slice string elements with [:2]
, but you can use astype
to truncate the strings:
JavaScript
1
7
1
In [306]: alist = ["IS-2","AT-3","IS-4"]
2
In [307]: np.array(alist)
3
Out[307]: array(['IS-2', 'AT-3', 'IS-4'], dtype='<U4')
4
5
In [309]: np.array(alist).astype('U2')
6
Out[309]: array(['IS', 'AT', 'IS'], dtype='<U2')
7
The resulting array could be tested against ‘IS’ etc:
JavaScript
1
5
1
In [310]: np.array(alist).astype('U2')=='IS'
2
Out[310]: array([ True, False, True])
3
In [311]: np.array(alist).astype('U2')=='AT'
4
Out[311]: array([False, True, False])
5
Using two where
steps:
JavaScript
1
5
1
In [312]: np.where(Out[309]=='IS', "ok-CHOICE ONE", Out[307])
2
Out[312]: array(['ok-CHOICE ONE', 'AT-3', 'ok-CHOICE ONE'], dtype='<U13')
3
In [313]: np.where(Out[309]=='AT', "NOTok", Out[312])
4
Out[313]: array(['ok-CHOICE ONE', 'NOTok', 'ok-CHOICE ONE'], dtype='<U13')
5
np.select
could probably used as well.