1

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 
8
  • 4
    Please include a sample of data and your expected output. Commented Nov 15, 2021 at 18:20
  • @not_speshal Just added a picture of the data file, Commented Nov 15, 2021 at 18:24
  • @not_speshal Ok, sorry i tried to attach it, but could not, Commented Nov 15, 2021 at 18:25
  • Is your file just one line? Commented Nov 15, 2021 at 18:28
  • Side note: eval is very dangerous, but your data looks like valid JSON (when the comment is removed). You could use json.loads instead. Commented Nov 15, 2021 at 18:30

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, would it be possible also to get the last two characters, (which are numbers (integer in that case ??) Thanks again
0

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

1 Comment

Can not we do like my earlier code, as the file will contain other lines , and do not wanna change read approach ?? Also, I am wondering not other way to read index inside index as I wanna
0

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

2 Comments

Thank you very much for your feedback, mmm... I just would prefer to use numpy as I have a lot of other inputs and need them to be an array ? Also, in the above mentioned code, i got the following error: line 4, in <module> data = data.partition(' ')[0] AttributeError: 'list' object has no attribute 'partition'
You have string data. numpy doesn't really help you here. And clearly, if you are running through a LIST of such lines, then you need an outer loop. for row in my_data: / for i in row[0].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.