[英]Python cannot export to Stata due to unicode problem?
我正在嘗試將 Python 中的數據幀導出為 Stata 數據。 這是我正在使用的代碼的精簡版:
import pandas as pd
df_master = pd.read_stata(old_dta_location)
# Do some data manipulation.
df_master.to_stata(new_dta_location, {"final_date": "td"}, write_index = False)
執行此操作時出現以下錯誤:
UnicodeEncodeError: 'latin-1' codec can't encode character '\u20ac' in position 11: ordinal not in range(256)
我知道還有其他關於 unicode 錯誤的問題,但由於它們與 Stata 無關,因此諸如放置像 'encoding = "utf8"' 這樣的參數的選項不起作用。
我怎樣才能解決這個問題?
默認情況下,pandas 導出到不支持 unicode 的 Stata 版本 10(代碼 114)。
只需指定更高的 Stata 版本 (118+) 即可正確導出 unicode 列:
df = pd.DataFrame({'animal': ['€falcon', '€parrot', '€falcon','€parrot']})
df.to_stata('animals.dta', version=118)
Stata 文件可以接受 UTF-8 數據,只是to_csv
堅持使用不包含€
字符的 Latin-1 編碼。 一種可能的解決方法是直接使用StataWriterUTF8
對象:
w = pd.io.stata.StataWriterUTF8('foo.dta', df_master)
w.write_file()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.