python - 从 pandas.read_sql 读取时编码 impala 数据
问题描述
当我使用pyhive
库读取 impala 数据pandas.read_sql
时出现错误UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe2 in position 3071: unexpected end of data
此错误的原因可能是那里的数据可能已损坏。
如何将其更改为不同的编码,以便我可以在数据框中获取数据?
解决方案
解决方法如下:
1)我们通过 Pyhive 游标逐块检索数据。
2)预处理:编码/解码。
3)附加到最终数据框。
# cursor to the database.
cursor = hive.Connection(host=HOST, port=PORT, username=USERNAME).cursor()
# execute the query on the database side.
cursor.execute("SELECT id, message FROM table")
# result dataframe, empty for now.
df = pd.DataFrame(columns=['id', 'message'])
while True:
# fetch 10k rows (as tuples).
rows = cursor.fetchmany(10000)
# if no more rows to retrieve, we stop.
if not rows:
break
# Preprocessing: do encoding/decoding here
rows = [(id, message.decode('utf-8', 'ignore')) for id, message in rows]
# put result in a temporary dataframe
df_tmp = pd.DataFrame(rows, columns=['id', 'message'])
# merge the temporary dataframe to the original df
df = pd.concat([df, df_tmp])
df = ...
推荐阅读
- python - 使用数据属性刮取元素的内容 - Python BeautifulSoup
- python - 将具有 2 个坐标的 Matplotlib Ray 扩展到图表边缘
- javascript - 在不影响游戏坐标的情况下居中画布元素
- sql - 如何使用 VBA 在 Excel 上“绕过”“受密码保护的 SQL Server 数据库”弹出窗口?
- google-sheets - 如何根据一周中的某一天设置条件格式?
- python - 为什么 np.linalg.eig() 和 np.linalg.eigh() 返回不同的特征向量?
- android - 属性委托必须有一个 'getValue(Nothing?, KProperty*>)' 方法
- google-sheets - 为什么 vlookup 搜索的是“44221”而不是“2021-01-25”?
- flutter - Flutter:检查文本字符串是否在网页中?
- html - 如何删除浏览器底部的意外滚动条