如何从添加的ndarray中删除“b”字符np.genfromtx公司

2024-10-04 11:36:25 发布

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

我有一个文本文件,它包含字符串、整数和浮点形式的信息行,用空格隔开,例如

HIP893 23 U 10 7 0.028 4
HIP1074 43_20 20 0.0141 1
HIP11325 23_10 7 0.02388 5
... 在

我已使用以下行导入此数据:

data=np.genfromtxt('98_info.txt', dtype=(object, object, int,float,float))

但是,当我这样做时,我得到的输出

^{pr2}$

我希望没有“b”,而是:

[('HIP893', '23_10', 7, 0.028, 4.0) 
 ('HIP1074', '43_20', 20, 0.0141, 1.0)
 ('HIP1325', '23_10', 7, 0.02388, 5.0)
  ... ]

我试过纽比的机芯、机芯但是这给了我一个错误“字符串操作在非字符串数组上”,我想是因为我的数据是字符串和数字的组合?在

是否有某种方法可以删除字符但将数据保留在数组中,或者也许有另一种方法来加载信息,使字符串保留在引号中,而没有引号的数字呢?在

如果有一种方法可以将它作为2d np数组导入,那就更好了,但如果不是的话,那就不是问题了。在

谢谢!在


Tags: 数据方法字符串信息objectnp数字整数
3条回答

您可以使用解码字节字符串的函数传递converters=,例如:

convs = dict.fromkeys([0, 1], bytes.decode)
data = np.genfromtxt('98_info.txt', dtype=(object, object, int, float, float), converters=convs)

这将给您data的:

^{pr2}$

您的样品和dtype

In [1]: np.genfromtxt('stack55810419.txt', dtype=(object, object, int,float,floa
   ...: t))                                                                     
Out[1]: 
array([(b'HIP893', b'23_10',  7, 0.028  , 4.),
       (b'HIP1074', b'43_20', 20, 0.0141 , 1.),
       (b'HIP1325', b'23_10',  7, 0.02388, 5.)],
      dtype=[('f0', 'O'), ('f1', 'O'), ('f2', '<i8'), ('f3', '<f8'), ('f4', '<f8')])

使用dtype=None(和encoding=None):

^{pr2}$

指定unicode数据类型(必须包括大小):

In [6]: np.genfromtxt('stack55810419.txt', dtype=('U7', 'U7', int,float,float)) 
Out[6]: 
array([('HIP893', '23_10',  7, 0.028  , 4.),
       ('HIP1074', '43_20', 20, 0.0141 , 1.),
       ('HIP1325', '23_10',  7, 0.02388, 5.)],
      dtype=[('f0', '<U7'), ('f1', '<U7'), ('f2', '<i8'), ('f3', '<f8'), ('f4', '<f8')])

我很困惑为什么None为第二列选择一个整型数据类型(下划线应该可以阻止这一点)。在

不带encoding参数的dtype=None将引发此警告:

/usr/local/bin/ipython3:1: VisibleDeprecationWarning: Reading unicode strings without specifying the encoding argument is deprecated. Set the encoding, use None for the system default.

在Py2中,默认的字符串类型是bytestrings;在py3unicode中。genfromtxt与py2兼容使用了bytestrings。但是最近的版本增加了encoding参数。但这种转变似乎仍有一些粗糙的边缘。在


这可能就是我得到i8;Python自己的int接受下划线的原因。在

In [20]: int('23_10')                                                           
Out[20]: 2310

后跟b的字符串是编码字符串,即在bytes

您可以通过应用decode函数或仅使用str来解码它们

newData = [(str(x) if isinstance(x,bytes) else x for x in y) for y in data]

我想你可以通过this在nparray中转换它,所以回答

I really don't know about nparray

相关问题 更多 >