【问题标题】:Pandas read_excel strange error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2Pandas read_excel 奇怪的错误:UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2
【发布时间】:2015-06-27 18:40:09
【问题描述】:

当我在 IPython(或者确切地说是 Jupyter)中读取一个 excel 文件时,数据框似乎可以读取,但我无法显示它或处理它上面的文本列(例如,与另一个 excel 合并当键是文本字段时),因为我得到一个“

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2...

错误

奇怪的是,如果我这样做:

for i in df['Textual Col Name']:
    print i

它会打印所有的值。

我在这里尝试了针对其他类似问题提供的不同解决方案,但没有任何效果。当从 excel 文件中读取 df 时,我认为 SO 没有一个好的答案。

很想就如何解决这个问题得到您的帮助,如果可能的话,还想解释一下为什么我说的和做的我仍然可以很好地打印单个项目。

提前致谢!

【问题讨论】:

    标签: python python-2.7 pandas ipython dataframe


    【解决方案1】:

    你需要指定文件的编码,没有文件是不可能知道它是如何编码的但你可以尝试一些,如果你不知道,看看哪个有效。encoding=tuf-8encoding=latin-1encoding=cp1252 中的pd.read_excel

    【讨论】:

      【解决方案2】:

      尝试使用二分法来隔离问题行:

      import numpy as np
      import pandas as pd
      
      # substitute your df here
      df = pd.DataFrame({'textcol':np.random.randint(10, size=[1000])})
      
      def isokay(df):
          try:
              print(df)
          except UnicodeDecodeError:
              return False
          return True
      
      i = 0
      chunksize = len(df) // 2
      while True:
          if isokay(df.iloc[i:i+chunksize]):
              i += chunksize
              if i > len(df):
                  print('No error found')
                  break
          else:
              if chunksize <= 1:
                  # Problem occurs at row i
                  print('Problem occurs on row {}'.format(i))
                  print(df.iloc[i])
                  break
              else:
                  chunksize /= 2
      

      print(df.iloc[i]) 行可能会导致错误。如果是这样,您可以查阅 excel 文件以了解行 i 中包含哪些数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-16
        • 1970-01-01
        • 2016-05-05
        • 2013-12-31
        • 2018-07-29
        • 2018-11-02
        • 1970-01-01
        相关资源
        最近更新 更多