首页 > 解决方案 > 将具有 dtypes datetime64[ns] 和 timedelta64[ns] 的数据帧导入到 google bigquery 表

问题描述

我想从具有以下数据类型的数据框中更新 bigquery 表:

datetime64[ns]
timedelta64[ns]

实现这一目标的适当方法是什么?

我有一个包含以下两列和数据的数据框。

我们称之为 timestamps_df

   timestamp                  timeInStatus
0   2019-01-02 21:30:20.769     0 days 00:00:00
1   2019-11-04 17:23:59.728     305 days 19:53:38.959000
2   2019-11-04 17:24:03.613     0 days 00:00:03.885000
3   2019-11-04 17:24:07.015     0 days 00:00:03.402000
4   2019-01-08 19:41:31.706     0 days 00:00:00
5   2019-01-21 19:56:05.031     13 days 00:14:33.325000
6   2019-04-19 16:24:49.219     87 days 20:28:44.188000
7   2019-04-19 16:24:51.948     0 days 00:00:02.729000
8   2019-05-03 08:46:47.079     0 days 00:00:00
9   2019-05-03 08:46:50.072     0 days 00:00:02.993000

当我调用 timestamps_df.dtypes 它返回以下

time_stamp_update     datetime64[ns]
time_in_status       timedelta64[ns]
dtype: object

我想使用 Google.cloud 库导入 bigquery 将其发布到 bigquery 表中。当我使用 CSV 手动加载表时,我看到 bigquery 中的自动检测字段列为:

时间戳 = TIMESTAMP timeInStatus = STRING

#sets the table to be updated in bigquery
table_id = "projectName.dataSetName.tableName"


#sets the datatypes for the bigquery table
job_config = bigquery.LoadJobConfig(
    schema=[
        bigquery.SchemaField("timestamp", bigquery.enums.SqlTypeNames.TIMESTAMP),
        bigquery.SchemaField("timeInStatus", bigquery.enums.SqlTypeNames.STRING)
    ],
    # Optionally, set the write disposition. BigQuery appends loaded rows
    # to an existing table by default, but with WRITE_TRUNCATE write
    # disposition it replaces the table with the loaded data.
    write_disposition="WRITE_TRUNCATE",
)

job = client.load_table_from_dataframe(timestamps_df, table_id, job_config=job_config)
job.result()  # Wait for the job to complete.

有任何想法吗?到目前为止,我已经尝试了一些事情,但我真的很想保持数据看起来与它已经是相同的格式。

标签: pythonpandasdatetimegoogle-bigquery

解决方案


BigQuery 中没有“TIMEDELTA”数据类型,您可以参考 [1] 来检查可能的数据类型。

一种解决方法可能是以适合“TIME”类型 [2] 的方式预处理您的“timeInStatus”列。

但是,如果您受限于保持实际格式,则可以对 BigQuery 使用“STRING”类型,如果需要将表导入 Python 环境,则使用 [3]。

[1] https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types

[2] https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#time_type

[3] https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_timedelta.html


推荐阅读