genfromtxt()中的NumPy dtype问题,以bytestring的形式读取字符串

2024-06-01 10:03:23 发布

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

我想把一个标准的ascii csv文件读入numpy,这个文件由float和string组成。

例如

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',但在这里没有什么真正的帮助。

恐怕,但我想我只是不明白数据类型转换是如何工作的…如果你能在这里给我一些提示就好了!

谢谢


Tags: 文件csv字符串numpy标准asciic2dtype
3条回答

在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字节。


v 1.14的变化:https://docs.scipy.org/doc/numpy/release.html#encoding-argument-for-text-io-functions

np.genfromtxt(csv_file, dtype='|S12', delimiter=',')

或者可以使用usecols参数选择已知为字符串的列:

np.genfromtxt(csv_file, dtype=None, delimiter=',',usecols=(0,1,2,4))

在Python3.6中

all_data = np.genfromtxt(csv_file.csv, delimiter=',', dtype='unicode')

工作得很好。

相关问题 更多 >