zoukankan      html  css  js  c++  java
  • 关于loadtxt编码问题的解决方法

    I am trying to load data with numpy.loadtxt... The file im trying to read is using cp1252 coding. Is there a possibility to change the encoding to cp1252 with numpy?

    The following

    import numpy as np
    n = 10
    myfile = '/path/to/myfile'
    mydata = np.loadtxt(myfile, skiprows = n)
    

    gives:

    UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 189: invalid start byte
    

    The file contains metadata (first n rows) followed by a table of floats.

    Edit: This problem only occurs when running this on Ubuntu (12.04). On Windows it works well. For this reason I think this problem is related to the encoding.

    Edit2: opening the file as shown in the following works well, too:

    import codecs
    data = codecs.open(myfile, encoding='cp1252')
    datalines = data.readlines()
    

    However I'd like to use np.loadtext to directly read the data into a numpy array.

     --------------------------------------------------------------------------------------

    I could solve the problem by myself.

    I just had to open the file with the appropriate before reading it with numpy:

    import numpy as np
    import codecs
    
    n=10
    
    filecp = codecs.open(myfile, encoding = 'cp1252')
    mydata = np.loadtxt(filecp, skiprows = n)
    

    Thank you everyone!

     
  • 相关阅读:
    SpringBoot自定义starter
    Vue中$nextTick()用法
    Vue中filters使用data的数据
    Vue页面生成二维码
    Vue页面实现打印功能
    Vue中监听(watch)的使用
    Vue中判断对象属性是否存在
    大三寒假学习进度(十九)
    大三寒假学习进度(十八)
    大三寒假学习进度(十七)
  • 原文地址:https://www.cnblogs.com/master-road/p/10422214.html
Copyright © 2011-2022 走看看