【问题标题】:TypeError: Text reading control character must be a single unicode character or NoneTypeError:文本读取控制字符必须是单个 unicode 字符或无
【发布时间】:2022-11-11 19:03:52
【问题描述】:

从分隔符中包含多个字符的文件加载时,使用 numpy.loadtxtnumpy==1.23.4 会引发 TypeError

from io import StringIO
import numpy as np

csv_file = StringIO("""1, 2
3, 4
5, 6
""")

print(np.loadtxt(csv_file, delimiter=", "))
Traceback (most recent call last):
  File "/home/hayesall/Teaching/questions/nploadtxt/testing.py", line 9, in <module>
    print(np.loadtxt(csv_file, delimiter=", "))
  File "/home/hayesall/miniconda3/envs/timeseries/lib/python3.10/site-packages/numpy/lib/npyio.py", line 1318, in loadtxt
    arr = _read(fname, dtype=dtype, comment=comment, delimiter=delimiter,
  File "/home/hayesall/miniconda3/envs/timeseries/lib/python3.10/site-packages/numpy/lib/npyio.py", line 979, in _read
    arr = _load_from_filelike(
TypeError: Text reading control character must be a single unicode character or None; but got: ', '

对于numpy==1.22.4,这似乎不会发生:

[[1. 2.]
 [3. 4.]
 [5. 6.]]

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    loadfromtxtappears to have been rewritten1.221.23 之间。

    一种解决方法是将np.loadtxt 替换为np.genfromtxt

    from io import StringIO
    import numpy as np
    
    csv_file = StringIO("""1, 2
    3, 4
    5, 6
    """)
    
    print(np.genfromtxt(csv_file, delimiter=", "))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-06
      • 1970-01-01
      • 1970-01-01
      • 2020-05-05
      • 2019-11-04
      • 2017-04-12
      • 2013-05-25
      相关资源
      最近更新 更多