【问题标题】:ValueError: size of tuple must match number of fields while using genfromtxtValueError:使用 genfromtxt 时,元组的大小必须与字段数匹配
【发布时间】:2017-07-02 17:35:25
【问题描述】:
import os
import numpy as np
os.getcwd()
os.chdir('C:/Users/Gururaj/Desktop/tech/python/')
data = np.genfromtxt("simple.txt", dtype=None, delimiter=",", 
names=str(False))
print(data[0])

==========================错误如下=================== ===

这是在 Jupyter notebook for python 3 中完成的

  ValueError                                Traceback (most recent call 
  last)
  <ipython-input-34-c2ba85f75012> in <module>()
  3 os.getcwd()
  4 os.chdir('C:/Users/Gururaj/Desktop/tech/python/')
  ----> 5 data = np.genfromtxt("simple.txt", dtype=None, delimiter=",", 
  names=str(False))
  6 print(data[0])

  C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\npyio.py in 
  genfromtxt(fname, dtype, comments, delimiter, skip_header, skip_footer, 
  converters, missing_values, filling_values, usecols, names, excludelist, 
  deletechars, replace_space, autostrip, case_sensitive, defaultfmt, unpack, 
  usemask, loose, invalid_raise, max_rows)
  1874             ddtype = list(zip(names, column_types))
  1875             mdtype = list(zip(names, [np.bool] * len(column_types)))
  -> 1876         output = np.array(data, dtype=ddtype)
  1877         if usemask:
  1878             outputmask = np.array(masks, dtype=mdtype)

  ValueError: size of tuple must match number of fields.
  ===========================================================
  Data in file:
  this,is,me,learning
  monty,pythons,flying,circus
  sounds,exciting,but,hmm

请提供帮助,因为我现在才开始学习 Python 基础知识。

【问题讨论】:

    标签: python numpy ipython ipython-notebook genfromtxt


    【解决方案1】:

    genfromtxt 文档说:

    名称:{None, True, str, sequence}

    您将其设置为:

    In [689]: str(False)
    Out[689]: 'False'
    

    换句话说,您告诉它将一个字段命名为“False”。因此字段数和列数不匹配。

    我怀疑你想要names=None,意思是不要从文件中取字段名。

    【讨论】:

    • 谢谢。你能告诉我为什么输出,当我运行单元格时,会出现带有'b'前缀的:[b'monthy' b'pythons' b'flying' b'circus']
    • b 前缀表示 Py3 中的字节串,其中 unicode 是默认的 dtype。 S10 是 10 个字符的 bytestring dtype,U10 是 10 个字符的 unicode dtype。
    猜你喜欢
    • 2022-11-23
    • 2017-10-17
    • 2021-03-07
    • 1970-01-01
    • 2019-03-28
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 2020-02-23
    相关资源
    最近更新 更多