使用 spark.read.csv
和 encoding='utf-8'
将包含外来字符 (åäö) 的数据帧加载到 Spark 中,并尝试做一个简单的展示().
>>> df.show()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/spark/python/pyspark/sql/dataframe.py", line 287, in show
print(self._jdf.showString(n, truncate))
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 579: ordinal not in range(128)
我认为这可能与 Python 本身有关,但我无法理解所提到的任何技巧 here for example可以在 PySpark 和 show() 函数的上下文中应用。
最佳答案
https://issues.apache.org/jira/browse/SPARK-11772谈论这个问题并给出了一个运行的解决方案:
export PYTHONIOENCODING=utf8
在运行 pyspark
之前。我想知道为什么上面的方法有效,因为即使没有它,sys.getdefaultencoding()
也为我返回了 utf-8
。
How to set sys.stdout encoding in Python 3?还讨论了这一点并为 Python 3 提供了以下解决方案:
import sys
sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf8', buffering=1)
关于python - PySpark — UnicodeEncodeError : 'ascii' codec can't encode character,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46763249/