我有这个:
>>> 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']`
但是我需要列
`matriz[:, [2]] :
[['198'],
['232'],
['180'],
['255']]`
设为int,其他列设为字符串,我尝试使用结构化numpy数组,但出现此错误消息,
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')
我正在为pi pi 3使用numpy版本“ 1.12.1”,我不知道自己在做什么错。 非常感谢
答案 0 :(得分:1)
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
转换来获取最后一列:
In [485]: x[:,2].astype(int)
Out[485]: array([198, 232, 180, 255])
In [486]: x[:,[2]].astype(int)
Out[486]:
array([[198],
[232],
[180],
[255]])
要构建结构化数组,您需要提供一个元组列表。具有复合dtype的列表或非结构化数组的列表会产生您的错误。
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])
结构化数组的字段按名称获取。
答案 1 :(得分:0)
NumPy最适合同构dtype数组。如果您使用其他类型的熊猫,Pandas是一个不错的选择。
但是,使用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')])