13

我想将标准 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
...

无论我尝试什么,生成的数组看起来像

例如,

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'or dtype='a25,a25,a25,f,a25',但这里没有任何帮助。

我很害怕,但我想我只是不明白 dtype 转换是如何工作的......如果你能在这里给我一些提示会很好!

谢谢

4

3 回答 3

6

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

于 2014-02-22T21:01:01.480 回答
6

在 python 3.6 中,

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

工作得很好。

于 2017-05-16T20:00:27.777 回答
4
np.genfromtxt(csv_file, dtype='|S12', delimiter=',')

或者您可以使用参数选择您知道是字符串的列usecols

np.genfromtxt(csv_file, dtype=None, delimiter=',',usecols=(0,1,2,4))
于 2014-02-22T18:53:49.910 回答