【发布时间】:2023-04-05 18:39:01
【问题描述】:
我想从具有以下数据类型的数据框中更新 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 中的自动检测字段被列为:
时间戳 = 时间戳 timeInStatus = 字符串
#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.
有什么想法吗?到目前为止,我已经尝试了一些方法,但我真的希望保持数据的格式与现有格式相同。
【问题讨论】:
-
取决于您想对
timeInStatus数据做什么,不是吗?不确定 google-bigquery 是否具有持续时间/时间增量的数据类型,但您可以肯定地将其转换为 pandas 中的浮点数,使用total_seconds()方法为您提供时间增量的总秒数。
标签: python pandas datetime google-bigquery