【问题标题】:python - numpy loadtxt, define type for specific columnspython - numpy loadtxt,为特定列定义类型
【发布时间】:2017-02-04 01:39:26
【问题描述】:

我对 python 3.x 有疑问 已知Python3读取字节串为:b'yourString'

我的问题是我想读取一个文本文件,用逗号分隔,四列应该是字符串,另一列是 intfloat

我知道有:

data_files=np.genfromtxt(i, names=True, dtype=None, delimiter=",")

我想做一些类似的事情(我知道这不起作用):

data_files=np.genfromtxt(i, names=True, dtype='None,str', delimiter=",",usecols=(0,2,3,4,5,6,8,9,11,12,14,15,16,17,18,19,20,21,22)(1,7,10,13))

我试过了:

alttype = np.dtype('f','s2','i2','i2','f0','f0','f0','s1','f0','f0','s1','f0','f0','s1','f0','f0','f0','f0','f0','f0','f0','f0','f0')

但这仅限于四组长。我不能把它们都读成str,因为我之后会对数字进行操作

任何帮助将不胜感激。

【问题讨论】:

  • 请提供数据(样本)的链接,这样更容易为您提供帮助。
  • 原始dtype=None 结果有什么问题?我不明白这个four sets long 位。两个genfromtxt 加载怎么样,一个用于字符串列,一个用于数字列?
  • 你好 B.M 很抱歉,我无法提供这些数据:/ @hpaulj,我希望能够做到这一点,然后合并它们,但我得到了 TypeError: invalid type promotion

标签: python numpy types


【解决方案1】:
In [365]: alttype = np.dtype('f','s2','i2','i2','f0','f0','f0','s1','f0','f0','s1','f0','f0','s1','f0','f0','f0','f0','f0','f0','f0','f0','f0')
...
TypeError: function takes at most 4 arguments (23 given)

dtype 的参数可以有多种形式,一个字符串,一个元组列表,几个字典。它反对参数的性质,而不是您尝试定义的字段数量。此外,genfromtxtdtype 更灵活。这种格式经常使用:dtype="i8,f8,S5"

所以alttype = 'f,S2,i,i,f,f,f,S1,...' 可能会起作用。不要使用f0

定义一个小样本“文件”(genfromtxt 接受行列表):

In [382]: txt=b"""A B C D E F G
     ...: a 23 2.1 c 2 3 7
     ...: b 22 2.0 d 2 5 8
     ...: """

默认加载:

In [384]: np.genfromtxt(txt.splitlines(),names=True,dtype=None)
Out[384]: 
array([(b'a', 23,  2.1, b'c', 2, 3, 7), 
       (b'b', 22,  2. , b'd', 2, 5, 8)], 
      dtype=[('A', 'S1'), ('B', '<i4'), ('C', '<f8'), ('D', 'S1'), ('E', '<i4'), ('F', '<i4'), ('G', '<i4')])

只加载字符串列

In [385]: np.genfromtxt(txt.splitlines(),names=True,dtype=None, usecols=[0,3])
Out[385]: 
array([(b'a', b'c'), (b'b', b'd')], 
      dtype=[('A', 'S1'), ('D', 'S1')])

说明所选列的数据类型

In [387]: np.genfromtxt(txt.splitlines(),names=True,dtype='U3,U3,i2,f4', usecols=[0,3,1,2])
Out[387]: 
array([('a', 'c', 23,  2.0999999), 
       ('b', 'd', 22,  2.       )], 
      dtype=[('A', '<U3'), ('D', '<U3'), ('B', '<i2'), ('C', '<f4')])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    • 2014-06-08
    • 1970-01-01
    相关资源
    最近更新 更多