栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

genfromtxt()中的NumPy 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中的“常规”字符串是unipre。但是您的文本文件具有字节字符串。

all_data
在这两种情况下都是相同的(136个字节),但是Python3显示字节字符串的方式是
b'C.3'
,而不仅仅是’C.3’。

您打算对这些字符串进行哪些类型的操作?

'ZIN' in all_data['f0'][1]
适用于2.7版本,但在3中必须使用
b'ZIN' inall_data['f0'][1]

numpy中的可变/未知长度字符串/ unipre
dtype

提醒我,您可以在中指定unipre字符串类型

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.7中

all_data_u
显示为

(u'ZINC00043096', u'C.3', u'C1', -0.154, u'methyl')

all_data_u
是448个字节,因为
numpy
为每个unipre字符分配了4个字节。每个
U4
项目长16个字节。


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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/669731.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号