Python2.7中
array([('ZINC00043096', 'C.3', 'C1', -0.154, 'methyl'),
('ZINC00043096', 'C.3', 'C2', 0.0638, 'methylene'),
('ZINC00043096', 'C.3', 'C4', 0.0669, 'methylene'),
('ZINC00090377', 'C.3', 'C7', 0.207, 'methylene')],
dtype=[('f0', 'S12'), ('f1', 'S3'), ('f2', 'S2'), ('f3', '<f8'), ('f4', 'S9')])
在 Python3
array([(b'ZINC00043096', b'C.3', b'C1', -0.154, b'methyl'),
(b'ZINC00043096', b'C.3', b'C2', 0.0638, b'methylene'),
(b'ZINC00043096', b'C.3', b'C4', 0.0669, b'methylene'),
(b'ZINC00090377', b'C.3', b'C7', 0.207, b'methylene')],
dtype=[('f0', 'S12'), ('f1', 'S3'), ('f2', 'S2'), ('f3', '<f8'), ('f4', 'S9')])
Python3 中的“常规”字符串是 unicode。但是您的文本文件有字节字符串。 all_data
在这两种情况下都是相同的(136 字节),但 Python3 显示字节字符串的方式是b'C.3'
,而不仅仅是 'C.3'。
您打算对这些字符串进行哪些操作?'ZIN' in all_data['f0'][1]
适用于 2.7 版本,但在 3 中您必须使用b'ZIN' in all_data['f0'][1]
.
numpy 中的可变/未知长度字符串/unicode dtype
提醒我,您可以在dtype
. 但是,如果您事先不知道字符串的长度,这会变得更加复杂。
alttype = np.dtype([('f0', 'U12'), ('f1', 'U3'), ('f2', 'U2'), ('f3', '<f8'), ('f4', 'U9')])
all_data_u = np.genfromtxt(csv_file, dtype=alttype, delimiter=',')
生产
array([('ZINC00043096', 'C.3', 'C1', -0.154, 'methyl'),
('ZINC00043096', 'C.3', 'C2', 0.0638, 'methylene'),
('ZINC00043096', 'C.3', 'C4', 0.0669, 'methylene'),
('ZINC00090377', 'C.3', 'C7', 0.207, 'methylene')],
dtype=[('f0', '<U12'), ('f1', '<U3'), ('f2', '<U2'), ('f3', '<f8'), ('f4', '<U9')])
在 Python2.7all_data_u
中显示为
(u'ZINC00043096', u'C.3', u'C1', -0.154, u'methyl')
all_data_u
是 448 字节,因为numpy
为每个 unicode 字符分配 4 个字节。每个U4
项目长 16 个字节。
v 1.14 中的更改:https ://docs.scipy.org/doc/numpy/release.html#encoding-argument-for-text-io-functions