gpt4 book ai didi

python - 定义 table_schema 时无法将具有 NaN(或 None)值的 Pandas 数据帧插入 BigQuery 表中

转载 作者:太空宇宙 更新时间:2023-11-03 19:42:00 27 4
gpt4 key购买 nike

我正在使用 pandas_gbq.to_gbq()DataFrame 导出到 Google BigQuery,其中 col1 具有 NULL 值。

>>>df
col1 day
apple 2019-03-01
None 2019-03-02
banana 2019-03-02
None 2019-03-03

>>>df.dtypes
col1 object
day datetime64[ns]
dtype: object

在不定义表架构的情况下,我能够成功导出 BigQuery 中的表,并在 col1 中使用 null 值。

from google.cloud import bigquery
import pandas as pd
import pandas_gbq

pandas_gbq.to_gbq(df
,table_name
,project_id='project-dev'
,chunksize=None
,if_exists='replace'
)

BigQuery 中的默认表架构:

col1   STRING      NULLABLE
day TIMESTAMP NULLABLE

但是,当我尝试在 BigQuery 中将 day 定义为 DATE 类型(因为我不需要 TIMESTAMP 类型)时,我遇到了错误(我尝试过 NaN 和 None;都遇到了错误)。

table_schema = [{'name':'day', 'type':'DATE'}]

pandas_gbq.to_gbq(df
,table_name
,project_id='project-dev'
,chunksize=None
,if_exists='replace'
,table_schema=table_schema
)

错误消息:

in df ,table_schema=table_schema File "/Users/xxx/anaconda3/lib/python3.6/site-packages/pandas_gbq/gbq.py", line 1224, in to_gbq progress_bar=progress_bar, File "/Users/xxx/anaconda3/lib/python3.6/site-packages/pandas_gbq/gbq.py", line 606, in load_data self.process_http_error(ex) File "/Users/xxx/anaconda3/lib/python3.6/site-packages/pandas_gbq/gbq.py", line 425, in process_http_error raise GenericGBQException("Reason: {0}".format(ex)) pandas_gbq.gbq.GenericGBQException: Reason: 400 Error while reading data, error message: CSV table encountered too many errors, giving up. Rows: 1; errors: 1. Please look into the errors[] collection for more details.

我已经阅读了 pandas_gbq 的文档,但我仍然无法弄清楚。

https://pandas-gbq.readthedocs.io/en/latest/api.html#pandas_gbq.to_gbq

有人能指出我正确的方向吗?谢谢。

最佳答案

我根据评论部分中提供的建议写下这个答案。

根据documentation ,如果您提供规范 DATE 格式的字符串,它将在 BigQuery 中被读取为 DATE。规范格式如下:

  • YYYY: Four-digit year

  • [M]M: One or two digit month

  • [D]D: One or two digit day

因此,按照上述方式更改类型和格式后,您将能够根据需要定义架构,否则 BigQuery 会将其识别为 DATE。

正如我在评论中提到的,我已经运行了一些测试来确认并举例说明我的建议,我将分享代码只是为了进一步帮助社区。我在AI平台中使用Jupyter Notebook运行了以下示例代码:

!pip install pandas_gbq

from google.cloud import bigquery
import pandas as pd


table_schema = [{'name':'my_datetime', 'type':'DATE'},{'name':'my_string', 'type':'string'}]
df = pd.DataFrame(
{
"my_datetime": ["2020-01-01", "2020-01-01", "2020-01-01"],
"my_string": ['a1',None, 'a3'],
}
)

df.to_gbq(destination_table='data_frame.data_set', project_id='project_id', if_exists='replace')

希望对您有所帮助。

关于python - 定义 table_schema 时无法将具有 NaN(或 None)值的 Pandas 数据帧插入 BigQuery 表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60366474/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com