获取 python 数组中每个索引的前 2 个字符
get first 2 characters of each index in array in python
我正在尝试访问 python 中 numpy 数组中每个索引的前两个字母:
我读过以前的错误论坛“'int' object is not subscriptable ,我知道它;它不是一个字符串,但对于我的工作来说最好是 numpy.array 或者如果有人建议我做另一件事,请帮助,
这是我的代码:
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()
.dat 文件中要使用的数据:
[["IS-2","AT-3","IS-4"]] # TYPE OF GN
以此为起点。请注意处理多行的简单更改。
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")
输出:
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
尝试:
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")
输出:
IS-2: ok-CHOICE ONE
AT-3: NOT ok
IS-4: ok-CHOICE ONE
您无法使用 [:2]
有效地分割字符串元素,但您可以使用 astype
来截断字符串:
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')
生成的数组可以针对 'IS' 等进行测试:
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])
使用两个 where
步骤:
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
也可以使用。
我正在尝试访问 python 中 numpy 数组中每个索引的前两个字母: 我读过以前的错误论坛“'int' object is not subscriptable ,我知道它;它不是一个字符串,但对于我的工作来说最好是 numpy.array 或者如果有人建议我做另一件事,请帮助,
这是我的代码:
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()
.dat 文件中要使用的数据:
[["IS-2","AT-3","IS-4"]] # TYPE OF GN
以此为起点。请注意处理多行的简单更改。
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")
输出:
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
尝试:
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")
输出:
IS-2: ok-CHOICE ONE
AT-3: NOT ok
IS-4: ok-CHOICE ONE
您无法使用 [:2]
有效地分割字符串元素,但您可以使用 astype
来截断字符串:
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')
生成的数组可以针对 'IS' 等进行测试:
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])
使用两个 where
步骤:
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
也可以使用。