python-3.x - 在将 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 表中。有没有人有解决方法?
解决方案
将所有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
推荐阅读
- ios - 更改 AVAudioSession 的模式时,AVRoutePickerView 显示不正确的输出设备信息
- python - Python pandas 数据框:通过数据框 max 获取元组
- r - 为什么加载 Rserve() 包会导致“'CreateProcess' failed to run”错误?
- qt - 对 SaleForse 的 QT 请求,状态码为 0
- c# - DBContext 依赖注入不适用于天蓝色计时器功能
- c# - 在 ASP.NET Core 的 BackgroundService 中处理非托管回调
- vue.js - VueJS - 从 API 获取删除、编辑用户后如何保留用户 ID?
- javascript - 如何使用异步函数正确遍历数组
- javascript - 如何使命令所有者只有 Discord.js
- windows - Ansible SUBST 驱动机器范围