2017-08-12 51 views
0

我想,以確保有一列中的任何字符串的問題從我的數據幀headlampUnicodeDecodeError:'ascii'編解碼器,如何解決?

之所以稱爲Comment是因爲我想以後導出數據幀到Excel使用.to_excel()和Unicode誤差總是提高。

我已經在網上閱讀了很多資料,也在這裏解決了這個問題,但是到目前爲止我無法管理它。 我試圖通過使用像下面的代碼encode()解決,但是,我仍然有同樣的問題。

headlamp = part_dataframe(ro, 'PN 3D', '921') 
headlamp['Comment'] = headlamp.Comment.apply(lambda x: x.encode('ascii', 
'ignore')) 
headlamp['word'] = headlamp.Comment.str.split().apply(lambda x: 
pd.value_counts(x).to_dict()) 
len(headlamp) 

錯誤:

UnicodeDecodeError      Traceback (most recent call last) 
<ipython-input-57-29454fde650e> in <module>() 
    1 headlamp = part_dataframe(ro, 'PN 3D', '921') 
----> 2 headlamp['Comment'] = headlamp.Comment.apply(lambda x: 
x.encode('ascii', 'ignore')) 
    3 headlamp['word'] = headlamp.Comment.str.split().apply(lambda x: 
    4 pd.value_counts(x).to_dict()) 
    5 len(headlamp) 

C:\Users\Rafael\Anaconda2\envs\gl-env\lib\site- 
packages\pandas\core\series.pyc in apply(self, func, convert_dtype, args, 
**kwds) 
2218   else: 
2219    values = self.asobject 
-> 2220    mapped = lib.map_infer(values, f, convert=convert_dtype) 
2221 
2222   if len(mapped) and isinstance(mapped[0], Series): 

pandas\src\inference.pyx in pandas.lib.map_infer (pandas\lib.c:62658)() 

<ipython-input-57-29454fde650e> in <lambda>(x) 
    1 headlamp = part_dataframe(ro, 'PN 3D', '921') 
----> 2 headlamp['Comment'] = headlamp.Comment.apply(lambda x: 
x.encode('ascii', 'ignore')) 
    3 headlamp['word'] = headlamp.Comment.str.split().apply(lambda x: 
    4 pd.value_counts(x).to_dict()) 
    5 len(headlamp) 

UnicodeDecodeError: 'ascii' codec can't decode byte 0xb4 in position 71: 
ordinal not in range(128) 

我完全失去了在這個問題上,因此,任何幫助將不勝感激。

我使用Jupyter IPython的

+0

這是Python 2嗎?另外,請顯示完整的回溯,以便我們可以看到引發異常的行。 – lenz

+0

請注意,異常與* de *編碼有關,所以'encode'方法本身並沒有提高它。但是,如果這是Python 2,則可能涉及隱式解碼步驟(從「str」到「unicode」的自動強制轉換)。 – lenz

+0

我已經用完整的回溯更新了這個問題,關於你的2條評論,能否更好地解釋我?我的Python是2.7 –

回答

0

0xb4是反引號的Unicode字符:http://www.fileformat.info/info/unicode/char/00b4/index.htm

它看起來像有一個在你的輸入非ASCII字符。嘗試將其編碼爲utf-8,然後查看是否有幫助。

如果你仍然需要它ascii,你可以試試這個解決方案:Convert a Unicode string to a string in Python (containing extra symbols)

+0

謝謝你的幫助,沒有必要在ascii中,我只是嘗試不同的類型,看看哪一個會解決。我嘗試了你的兩個建議並仍然沒有工作,你有沒有其他建議?預先感謝您 –

+0

嘗試使用我發送的其他堆棧溢出鏈接的庫,並查看是否出現錯誤! – AetherUnbound

+0

我已經嘗試了一些關於該鏈接的sugestions,並且我無法使其工作。說實話,即使我做對了,我也不會。你能幫助我嗎?,你如何寫我的代碼,我寫在我的問題,以解決它根據你的建議 –