我想将标准 ascii csv 文件读入 numpy,它由 float 和字符串组成。
例如,
ZINC00043096,C.3,C1,-0.1540,methyl
ZINC00043096,C.3,C2,0.0638,methylene
ZINC00043096,C.3,C4,0.0669,methylene
ZINC00090377,C.3,C7,0.2070,methylene
...
无论我怎样尝试,结果数组看起来都是这样的
例如,
all_data = np.genfromtxt(csv_file, dtype=None, delimiter=',')
[(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')
但是,我想为字节字符串转换节省一个步骤,并且想知道如何直接将字符串列作为常规字符串读取。
我尝试了 numpy.genfromtxt() 文档中的几项操作,例如 dtype='S,S,S,f,S'
或 dtype='a25,a25,a25 ,f,a25'
,但这里没有任何帮助。
我很害怕,但我想我只是不明白 dtype 转换的真正工作原理......如果你能在这里给我一些提示,那就太好了!
谢谢
最佳答案
在 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]
。
Variable/unknown length string/unicode dtype in numpy
提醒我您可以在 dtype
中指定一个 unicode 字符串类型。但是,如果您事先不知道字符串的长度,这会变得更加复杂。
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.7中all_data_u
显示为
(u'ZINC00043096', u'C.3', u'C1', -0.154, u'methyl')
all_data_u
为448字节,因为numpy
为每个unicode字符分配了4个字节。每个 U4
项的长度为 16 个字节。
1.14 版的变化:https://docs.scipy.org/doc/numpy/release.html#encoding-argument-for-text-io-functions
关于python - genfromtxt() 中的 NumPy dtype 问题,将字符串读取为 bytestring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21957667/