【问题标题】:ValueError: The elements are 0-sizedValueError:元素大小为 0
【发布时间】:2013-12-25 20:25:05
【问题描述】:

无法在网络上找到有关此问题的任何信息。我正在尝试使用 numpy 从文本文件中读取数据。

data = np.fromfile("C:\Users\Dan\Desktop\elements.txt",dtype=str,count=-1,sep=' ')

当我运行这段代码时,我得到了这个错误:

ValueError: The elements are 0-sized.

我以前从未见过此错误,Google 搜索未返回有关此错误的任何信息。为什么会出现此错误,我该如何解决?

编辑:这是文本文件的摘录

1   Hydrogen 1.008      
2   Helium  4.002602
3   Lithium 6.94    
4   Beryllium 9.0121831
5   Boron 10.81 
6   Carbon 12.011

【问题讨论】:

  • This 可能会有所帮助。一些源代码。 if (dtype->elsize == 0) 好像是你的敌人
  • 谢谢,我现在明白了。我不确定它实际上意味着什么,或者如何解决它。
  • 试试data = np.genfromtxt("C:\Users\Dan\Desktop\elements.txt", dtype=None)dtype=str
  • 解决了这个问题,谢谢。

标签: python arrays python-2.7 numpy text-files


【解决方案1】:

您最好将np.genfromtxt 用于文本文件; np.fromfile 更适合二进制文件。

这给出了您最初似乎想要的字符串数组:

>>> np.genfromtxt('tmp.txt', dtype=str)
array([['1', 'Hydrogen', '1.008'],
       ['2', 'Helium', '4.002602'],
       ['3', 'Lithium', '6.94'],
       ['4', 'Beryllium', '9.0121831'],
       ['5', 'Boron', '10.81'],
       ['6', 'Carbon', '12.011']], 
      dtype='|S9')

这为您提供了一个具有灵活 dtype 的记录数组:

>>> np.genfromtxt('tmp.txt', dtype=None)
array([(1, 'Hydrogen', 1.008), (2, 'Helium', 4.002602),
       (3, 'Lithium', 6.94), (4, 'Beryllium', 9.0121831),
       (5, 'Boron', 10.81), (6, 'Carbon', 12.011)], 
      dtype=[('f0', '<i8'), ('f1', 'S9'), ('f2', '<f8')])

但这就是我要做的,使用unpack 允许您分配给多个变量:

>>> n, name, mass = np.genfromtxt('tmp.txt', dtype='S', unpack=True)
>>> n = n.astype(int)
>>> mass = mass.astype(float)

【讨论】:

    猜你喜欢
    • 2020-07-19
    • 2022-01-08
    • 2020-04-01
    • 2022-07-06
    • 2022-11-23
    • 1970-01-01
    • 2017-07-28
    • 2021-06-14
    • 1970-01-01
    相关资源
    最近更新 更多