【问题标题】:how to convert a panda column into big query table date format如何将熊猫列转换为大查询表日期格式
【发布时间】:2021-06-22 20:17:39
【问题描述】:

我有一个熊猫数据框,其中有一列日期格式如下:

发布日期= 2018-08-31 我使用 panda to_gbq() 函数将数据转储到 bigquery 表中。在转储数据之前,我确保列的格式与表方案匹配。发布日期仅在 bigquery 表中是日期。如何实现类似于:

     df['PublishDate'] = df['PublishDate'].astype('?????')

我试过 datetime64[D] 和

     df['PublishDate'] = pd.to_datetime(df['PublishDate'], format='%Y-%m-%d', errors='coerce').dt.date
     df['PublishDate'] = [time.to_date() for time in df['PublishDate']]

但是那些没有用!

【问题讨论】:

    标签: python datetime google-bigquery


    【解决方案1】:

    我也遇到了同样的问题

    发现根据documentation可以提供

    table_schema : 字典列表,可选

    所以在我的情况下添加

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

    工作

    整行:

     pdg.to_gbq(table_for_uploading, upload_table, project_id=project_id, if_exists='replace', credentials=gbq_credentials,table_schema = [{'name':'execution_date','type': 'DATE'}])
    

    【讨论】:

    • 你是英雄。这也适用于日期时间,其他一切都失败了。
    【解决方案2】:

    Afaik,pandas-gbq doesn't seem to have support for the DATE type。因此,您最好的选择可能是将列导出为 TIMESTAMP,然后使用 SQL 查询将其转换为 DATE。

    df['PublishTimestamp'] = pd.to_datetime(
        df['PublishDate'],
        format='%Y-%m-%d',
        errors='coerce'
    )
    df.to_gbq("YOUR-DATASET.YOUR-TABLE", project_id="YOUR-PROJECT")
    
    client = bigquery.Client()
    
    job_config = bigquery.QueryJobConfig()
    table_ref = client.dataset("YOUR-DATASET").table("YOUR-TABLE")
    job_config.destination = ref_table
    job_config.write_disposition = "WRITE_TRUNCATE"
    
    sql = """
        SELECT
          *,
          DATE(PublishTimestamp) as PublishDate
        FROM
          `YOUR-PROJECT.YOUR-DATASET.YOUR-TABLE`
    """
    
    query_job = client.query(
        sql,
        job_config=job_config
    )
    query_job.result()
    

    【讨论】:

      【解决方案3】:

      我在 pandas-gbq 中找不到对日期类型的支持。

      另一种选择是使用 bigquery 客户端插入:

      from google.cloud import bigquery
      
      
      def chunks(l, chunk_size):
          for i in range(0, len(l), chunk_size):
              yield l[i:i + chunk_size]
      
      
      CLIENT_ROW_LIMIT = 10000
      SCHEMA = [
          bigquery.SchemaField('...'),
      ]
      
      def push_with_date(df):
          client = bigquery.Client(project='...')
          dataset = client.dataset('...')
          table_ref = dataset.table('...')
          rows = [row.tolist() for index, row in df.iterrows()]
          for i, chunk in enumerate(chunks(rows, CLIENT_ROW_LIMIT)):
              print('pushing', i)
              errors = client.insert_rows(table_ref, chunk, SCHEMA)
              if errors:
                  # Handle
                  raise Exception
      

      【讨论】:

        【解决方案4】:

        试试这个。这只是一种解决方法。 没有 to_gbq。

        job_config = bigquery.LoadJobConfig(
            schema=table_schema, source_format=bigquery.SourceFormat.CSV
        )
        load_job = bigquery_client.load_table_from_dataframe(
            dataframe, table_id, job_config=job_config
        )
        

        【讨论】:

          猜你喜欢
          • 2015-03-25
          • 2021-01-09
          • 2014-02-23
          • 2018-10-27
          • 2023-03-07
          • 2018-11-17
          • 2019-02-17
          • 2020-03-11
          • 2018-12-08
          相关资源
          最近更新 更多