【问题标题】:get first 2 characters of each index in array in python在python中获取数组中每个索引的前2个字符
【发布时间】:2021-12-26 22:25:32
【问题描述】:

我正在尝试访问 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 

【问题讨论】:

  • 请附上data 的样本和您的预期输出。
  • @not_speshal 刚刚添加了数据文件的图片,
  • @not_speshal 好的,抱歉,我试图附上它,但不能,
  • 你的文件只有一行吗?
  • 旁注:eval 非常危险,但您的数据看起来像有效的 JSON(删除评论时)。你可以改用json.loads

标签: python string numpy indexing


【解决方案1】:

您无法使用[: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 也可以使用。

【讨论】:

  • 非常感谢,是否也可以获取最后两个字符(它们是数字(在这种情况下为整数??)再次感谢
【解决方案2】:

将此作为起点。请注意处理多行的简单更改。

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

【讨论】:

  • 非常感谢您的反馈,嗯...我只是更喜欢使用 numpy,因为我有很多其他输入并且需要它们成为数组?此外,在上述代码中,我收到以下错误:第 4 行,在 data = data.partition(' ')[0] AttributeError: 'list' object has no attribute 'partition'
  • 你有字符串数据。 numpy 在这里并没有真正帮助你。显然,如果您正在运行此类行的 LIST,那么您需要一个外部循环。 for row in my_data: / for i in row[0].
【解决方案3】:

试试:

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

【讨论】:

  • 我们不能像我之前的代码那样做,因为文件将包含其他行,并且不想改变读取方法吗?另外,我想知道没有其他方法可以按照我的意愿读取索引内的索引
猜你喜欢
  • 2014-01-26
  • 1970-01-01
  • 2015-09-22
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
  • 2023-01-23
  • 1970-01-01
  • 2022-01-13
相关资源
最近更新 更多