【问题标题】:How to export numpy ndarray to a string variable?如何将 numpy ndarray 导出到字符串变量?
【发布时间】:2014-09-05 23:57:56
【问题描述】:

我正在尝试使用以下代码编写一个 xml 文件:

def make_xml(a_numpy_array):

    from lxml import etree as ET

    root = ET.Element('intersections')
    intersection = ET.SubElement(root, 'intersection')
    trace = ET.SubElement(intersection, 'trace')
    trace.text = a_numpy_array

    print ET.tostring(root, pretty_print=True, xml_declaration=True, encoding = 'utf-8')

.....

trace.text 需要一个字符串输入。我想在 xml 文件中放入一个存储为 numpy ndarray 的 2D 数组。但我似乎无法将数据导出为字符串。 numpy.tostring 给了我字节码,我该怎么办?我提出的解决方案是将 ndarray 写入文本文件,然后将文本文件作为字符串读取,但我希望能够跳过写入文本文件。

【问题讨论】:

    标签: python string numpy lxml elementtree


    【解决方案1】:

    你可以的

    trace.text = str(a_numpy_array)
    

    有关更多选项,请参阅numpy.array_strnumpy.array2string

    【讨论】:

      【解决方案2】:

      您可以使用np.savetxt 将数组写入io.BytesIO()(而不是文件)。

      import numpy as np
      from lxml import etree as ET
      import io
      
      root = ET.Element('intersections')
      intersection = ET.SubElement(root, 'intersection')
      trace = ET.SubElement(intersection, 'trace')
      
      x = np.arange(6).reshape((2,3))
      s = io.BytesIO()
      np.savetxt(s, x)
      trace.text = s.getvalue()
      
      print(ET.tostring(root, pretty_print=True, xml_declaration=True, encoding = 'utf-8'))
      

      产量

      <?xml version='1.0' encoding='utf-8'?>
      <intersections>
        <intersection>
          <trace>0.000000000000000000e+00 1.000000000000000000e+00 2.000000000000000000e+00
      3.000000000000000000e+00 4.000000000000000000e+00 5.000000000000000000e+00
      </trace>
        </intersection>
      </intersections>
      

      然后您可以使用np.loadtxt 将数据加载回 NumPy 数组:

      for trace in root.xpath('//trace'):
          print(np.loadtxt(io.BytesIO(trace.text)))
      

      产量

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-05
        相关资源
        最近更新 更多