首页 > 解决方案 > 在将 Pandas 数据帧插入 BigQuery 表时处理 NaN 值

问题描述

我正在使用以下代码将具有多个值的 Pandas 数据框插入NaN到 BigQuery 表中。数据框是在云 Datalab 中准备的。

import google.datalab.bigquery as bq

bqtable = ('project_name', 'dataset_name', 'table_name')
table = bq.Table(bqtable)

table_schema = bq.Schema.from_data(df)
table.create(schema = table_schema, overwrite = True)

table.insert(df)

NaN由于数据框中的值,我收到以下错误:

RequestException: HTTP request failed: Invalid JSON payload received. 
Unexpected token. : "user_id": NaN,
                               ^

我知道这JSON不明白NaN,但我不能只使用fillna将这些NaN值转换为其他值,因为我需要将这些字段插入null到 BigQuery 表中。有没有人有解决方法?

标签: python-3.xpandasdataframegoogle-bigquerygoogle-cloud-datalab

解决方案


将所有np.nan值替换为 python 的None值,然后重新运行您的代码(或尝试df.to_gbq):

df = df.where(pd.notnull(df), None)

我没有使用 Google BigQuery 的经验,我认为您现有的代码没有任何问题,但可能值得安装该pandas-gbq软件包。然后尝试使用 将 DataFrame 写入 GBQ df.to_gbq,详见此处的文档:https ://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_gbq.html


推荐阅读