我想在标准的ascii csv文件中读入numpy,它由浮点数和字符串组成.
例如,
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
...
Run Code Online (Sandbox Code Playgroud)
无论我尝试什么,结果阵列看起来都像
例如,
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')
Run Code Online (Sandbox Code Playgroud)
但是,我想保存字节字符串转换的步骤,并想知道如何直接在字符串列中读取常规字符串.
我尝试了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')])
Run Code Online (Sandbox Code Playgroud)
在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')])
Run Code Online (Sandbox Code Playgroud)
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
提醒我,您可以在中指定unicode字符串类型dtype
.但是,如果您事先不知道字符串的长度,则会变得更加复杂.
alttype = np.dtype([('f0', 'U12'), ('f1', 'U3'), ('f2', 'U2'), ('f3', '<f8'), ('f4', 'U9')])
all_data_u = np.genfromtxt(csv_file, dtype=alttype, delimiter=',')
Run Code Online (Sandbox Code Playgroud)
生产
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')])
Run Code Online (Sandbox Code Playgroud)
在Python2.7中all_data_u
显示为
(u'ZINC00043096', u'C.3', u'C1', -0.154, u'methyl')
Run Code Online (Sandbox Code Playgroud)
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
在python 3.6中,
all_data = np.genfromtxt('csv_file.csv', delimiter=',', dtype='unicode')
Run Code Online (Sandbox Code Playgroud)
工作得很好。
归档时间: |
|
查看次数: |
10362 次 |
最近记录: |