【问题标题】:Importing csv embedding special character with numpy genfromtxt使用 numpy genfromtxt 导入 csv 嵌入特殊字符
【发布时间】:2018-09-26 08:23:09
【问题描述】:

我有一个包含特殊字符的 CSV。一些单元格是算术运算(如“(10/2)”)。 我想使用 np.genfromtxt 将这些单元格作为字符串导入 numpy。 我注意到的是它实际上以 UTF8 导入它们(如果我理解的话)。例如,每次我有一个除法符号时,我都会在 numpy 数组中得到这个代码:\xc3\xb7

如何将这些算术运算导入为可读字符串?

谢谢!

【问题讨论】:

  • According to the docs, np.genfromtxtencoding 参数默认为"bytes",它“启用向后兼容性变通办法,确保您在可能的情况下接收字节数组并将拉丁1 编码的字符串传递给转换器。 "由于您有 UTF-8 文本,我猜想将此参数设置为 "utf8" 会产生您期望的输出。

标签: python csv numpy special-characters genfromtxt


【解决方案1】:

看起来文件可能有“其他”分隔符号,我们在小学学习的那个:

In [185]: b'\xc3\xb7'
Out[185]: b'\xc3\xb7'
In [186]: _.decode()
Out[186]: '÷'

最近的 numpy 版本可以更好地处理编码。早期的尝试完全以字节串模式(对于 Py3)工作以与 Py2 兼容。但现在它需要一个encoding 参数。

In [68]: txt = '''(10/2), 1, 2
    ...: (10/2), 3,4'''

In [70]: np.genfromtxt(txt.splitlines(), dtype=None, delimiter=',')
/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.
  #!/usr/bin/python3
Out[70]: 
array([(b'(10/2)', 1, 2), (b'(10/2)', 3, 4)],
      dtype=[('f0', 'S6'), ('f1', '<i8'), ('f2', '<i8')])

In [71]: np.genfromtxt(txt.splitlines(), dtype=None, delimiter=',',encoding=None
    ...: )
Out[71]: 
array([('(10/2)', 1, 2), ('(10/2)', 3, 4)],
      dtype=[('f0', '<U6'), ('f1', '<i8'), ('f2', '<i8')])

诚然,从字符串列表中模拟加载与从文件加载不同。我没有安装早期的 numpys(而不是在 Py2 上),所以无法显示之前发生的事情。但我的直觉是“(10/2)”以前不应该出现问题,至少在 ASCII 文件中不会出现问题。字符串中没有任何特殊字符。


与另一个鸿沟:

In [192]: txt = '''(10÷2), 1, 2
     ...: (10÷2), 3,4'''
In [194]: np.genfromtxt(txt.splitlines(), dtype=None, delimiter=',',encoding='ut
     ...: f8')
Out[194]: 
array([('(10÷2)', 1, 2), ('(10÷2)', 3, 4)],
      dtype=[('f0', '<U6'), ('f1', '<i8'), ('f2', '<i8')])

文件中的相同内容:

In [200]: np.genfromtxt('stack49859957.txt', dtype=None, delimiter=',')
/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.
  #!/usr/bin/python3
Out[200]: 
array([(b'(10\xf72)', 1, 2), (b'(10\xf72)', 3, 4)],
      dtype=[('f0', 'S6'), ('f1', '<i8'), ('f2', '<i8')])

In [199]: np.genfromtxt('stack49859957.txt', dtype=None, delimiter=',',encoding=
     ...: 'utf8')
Out[199]: 
array([('(10÷2)', 1, 2), ('(10÷2)', 3, 4)],
      dtype=[('f0', '<U6'), ('f1', '<i8'), ('f2', '<i8')])

在早期版本中,encoding 可以在 converter 中实现。我在之前的 SO 问题中帮助完成了这项任务。

【讨论】:

    猜你喜欢
    • 2015-10-04
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    相关资源
    最近更新 更多