在python中使用字符串和

2024-09-27 21:34:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个:

>>> matriz
      [['b8:27:eb:d6:e3:10', '0.428s', '198'],
      ['b8:27:eb:d6:e3:10', '0.428s', '232'],
      ['b8:27:eb:07:65:ad', '0.796s', '180'], 
      ['b8:27:eb:07:65:ad', '0.796s', '255'],
      dtype='<U17']`

但我需要专栏

^{pr2}$

对于int,而其他列是string,我尝试使用structured numpy array,但有一条错误消息

 ValueError: invalid literal for int() with base 10: 'b8:27:eb:d6:e3:10'
 TypeError: a bytes-like object is required, not 'str'

我用过

  matriz=np.array(matriz, dtype='U17,U17,i4')

我在用numpy版本的“1.12.1”来制作覆盆子皮3,我不知道我做错了什么。 非常感谢


Tags: numpystringarrayadintdtypestructuredeb
2条回答
In [484]: x = np.array([['b8:27:eb:d6:e3:10', '0.428s', '198'],
     ...:               ['b8:27:eb:d6:e3:10', '0.428s', '232'],
     ...:               ['b8:27:eb:07:65:ad', '0.796s', '180'], 
     ...:               ['b8:27:eb:07:65:ad', '0.796s', '255']],
     ...:              dtype='<U17')
     ...:              

您可以通过astype转换获取最后一列:

^{pr2}$

要构造结构化数组,需要提供元组列表。具有复合数据类型的列表或非结构化数组的列表将产生您的类型的错误。在

In [487]: np.array([tuple(i) for i in x],'U17,U10,int')
Out[487]: 
array([('b8:27:eb:d6:e3:10', '0.428s', 198),
       ('b8:27:eb:d6:e3:10', '0.428s', 232),
       ('b8:27:eb:07:65:ad', '0.796s', 180),
       ('b8:27:eb:07:65:ad', '0.796s', 255)],
      dtype=[('f0', '<U17'), ('f1', '<U10'), ('f2', '<i8')])
In [488]: _['f2']
Out[488]: array([198, 232, 180, 255])

按名称获取结构化数组的字段。在

NumPy与同构的dtype数组配合使用效果最好。熊猫是一个很好的选择,如果你有不同的类型。在

但是,对于NumPy structured arrays,您的要求是可能的:

import numpy as np

x = np.array([['b8:27:eb:d6:e3:10', '0.428s', '198'],
              ['b8:27:eb:d6:e3:10', '0.428s', '232'],
              ['b8:27:eb:07:65:ad', '0.796s', '180'], 
              ['b8:27:eb:07:65:ad', '0.796s', '255']],
             dtype='<U17')

arr = np.core.records.fromarrays(x.transpose(),
                                 formats='<U17,<U17,i4',
                                 names='col1,col2,col3')

print(arr)

rec.array([('b8:27:eb:d6:e3:10', '0.428s', 198),
           ('b8:27:eb:d6:e3:10', '0.428s', 232),
           ('b8:27:eb:07:65:ad', '0.796s', 180),
           ('b8:27:eb:07:65:ad', '0.796s', 255)],
          dtype=[('col1', '<U17'), ('col2', '<U17'), ('col3', '<i4')])

相关问题 更多 >

    热门问题