Skip to content
Advertisement

get first 2 characters of each index in array in python

enter image description here

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:

import numpy as np
import os
import os.path
with open('trial.dat', 'r') as f:
     data = f.readlines()
     data = [(d+' ')[:d.find('#')].rstrip() for d in data]

x=len(data[0])
x_1=eval(data[0])
y=np.concatenate(x_1)
print(type(y))
for i in range (x):
    if y[i[:2]]=='IS': # expected to be IS andso on.depened on the index
         print('ok-CHOICE ONE ')
elif y[i[:2]]=='AT':  
     print('NOTok ')
else:
     print()

Data to be used in the .dat file:

[["IS-2","AT-3","IS-4"]]                # TYPE OF GN 

Advertisement

Answer

You can’t efficiently slice string elements with [:2], but you can use astype to truncate the strings:

In [306]: alist = ["IS-2","AT-3","IS-4"]
In [307]: np.array(alist)
Out[307]: array(['IS-2', 'AT-3', 'IS-4'], dtype='<U4')

In [309]: np.array(alist).astype('U2')
Out[309]: array(['IS', 'AT', 'IS'], dtype='<U2')

The resulting array could be tested against ‘IS’ etc:

In [310]: np.array(alist).astype('U2')=='IS'
Out[310]: array([ True, False,  True])
In [311]: np.array(alist).astype('U2')=='AT'
Out[311]: array([False,  True, False])

Using two where steps:

In [312]: np.where(Out[309]=='IS', "ok-CHOICE ONE", Out[307])
Out[312]: array(['ok-CHOICE ONE', 'AT-3', 'ok-CHOICE ONE'], dtype='<U13')
In [313]: np.where(Out[309]=='AT', "NOTok", Out[312])
Out[313]: array(['ok-CHOICE ONE', 'NOTok', 'ok-CHOICE ONE'], dtype='<U13')

np.select could probably used as well.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement