2017-07-14 13 views
-4

私は非Unicode文字を_で置き換えようとしていますが、このプログラムはエラーなしでコンパイルしても問題は解決しません。UnicodeErrorは機能しません - Python

import csv 
import unicodedata 
import pandas as pd 

df = pd.read_csv('/Users/pabbott/Desktop/Unicode.csv', sep = ',', 
index_col=False, converters={'ClinetEMail':str, 'ClientZip':str, 
'LocationZip':str, 'LicenseeName': str, 'LocationState':str, 
'AppointmentType':str, 'ClientCity':str, 'ClientState':str}) 

data = df 
for row in data: 
    for val in row: 
     try: 
      val.encode("utf-8") 
     except UnicodeDecodeError: 
      replace(val,"_") 

data.to_csv('UnicodeExport.csv', sep=',', index=False, 
quoting=csv.QUOTE_NONNUMERIC) 
+0

表示されるエラーは何ですか? – MattR

+0

コードのダンプを投稿することは問題ではありません。 –

+0

新しいファイルでは、これらの非Unicode文字が_で正しく置き換えられませんが、コードが正しくコンパイルされるため、エラーは発生しません。私はそれがdata.apply関数に問題があるのだろうかと思いますか? –

答えて

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

pd.read_csvからスロー)上記のメッセージは、ファイルがutf-8に保存されていないことを示しています。あなたは

  • またはが適切なエンコーディングを使用してファイルを読み込み、 utf-8としてファイルを保存

    • いずれかする必要があります。次のよう

    インスタンス(後者の変形)について、df = pd.read_csv(…encoding='windows-1252'を追加します。

    df = pd.read_csv('/Users/pabbott/Desktop/Unicode.csv', sep = ',', encoding='windows-1252', 
    index_col=False, converters={'ClinetEMail':str, 'ClientZip':str, 
    'LocationZip':str, 'LicenseeName': str, 'LocationState':str, 
    'AppointmentType':str, 'ClientCity':str, 'ClientState':str}) 
    

    その後、あなたはfor row in data: for val in row:ループ内のすべてのもの try: val.encode("utf-8") を省略することができます。

    読むpandas.read_csv

    encoding : str , default None

    Encoding to use for UTF when reading/writing (ex. 'utf-8'). List of Python standard encodings .