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
CodePudding user response:
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.
CodePudding user response:
Try:
with open('trial.dat') as f:
line = f.readline() #readline (singular) since the file has only one line
data = [word.strip('"') for word in line.split("#")[0].strip(" []").split(",")]
for string in data:
if string.startswith("IS"):
print(f"{string}: ok-CHOICE ONE")
elif string.startswith("AT"):
print(f"{string}: NOT ok")
else:
print(f"{string}: Other")
Output:
IS-2: ok-CHOICE ONE
AT-3: NOT ok
IS-4: ok-CHOICE ONE
CodePudding user response:
Consider this as a starting point. Notice the simple change to handle multiple lines.
import json
data = """\
[["IS-2","AT-3","IS-4"]] # TYPE OF GN
[["IS-2","AT-3","IS-4"]] # TYPE OF GN
[["IS-2","AT-3","IS-4"]] # TYPE OF GN
[["IS-2","AT-3","IS-4"]] # TYPE OF GN"""
for row in data.splitlines():
row = row.partition(' ')[0]
row = json.loads( row)
for i in row[0]:
if i[:2] == "IS":
print(i,"OK" )
elif i[:2] == 'AT':
print(i, "NOT OK")
else:
print(i, "unknown")
Output:
IS-2 OK
AT-3 NOT OK
IS-4 OK
IS-2 OK
AT-3 NOT OK
IS-4 OK
IS-2 OK
AT-3 NOT OK
IS-4 OK