首页 > 解决方案 > 从 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

此错误的原因可能是那里的数据可能已损坏。

如何将其更改为不同的编码,以便我可以在数据框中获取数据?

标签: pythonpandasimpalapyhive

解决方案


解决方法如下:

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 = ...


推荐阅读