【问题标题】:How to control timestamp schema in pandas.to_parquet如何控制 pandas.to_parquet 中的时间戳模式
【发布时间】:2020-09-24 02:03:54
【问题描述】:

我注意到pandas.to_parquet 生成的 parquet 文件中 timestamp 的列类型可能因 pandas 的版本而异,例如

In [1]: pd.__version__                                                                                                 
Out[1]: '1.0.5'


In [2]: pd.DataFrame([pd.Timestamp('2020-01-01')], columns=['a']).to_parquet('/tmp/test.parquet')                      

In [3]: !parquet-tools schema /tmp/test.parquet                                                                        
message schema {
  optional int64 a (TIMESTAMP_MILLIS);
}

In [4]: !parquet-tools head /tmp/test.parquet                                                                          
a = 1577836800000
In [1]: pd.__version__
Out[1]: '1.1.2'

In [2]: pd.DataFrame([pd.Timestamp('2020-01-01')], columns=['a']).to_parquet('/tmp/test.parquet')

In [3]: !parquet-tools schema /tmp/test.parquet
message schema {
  optional int64 a (TIMESTAMP_MICROS);
}

In [4]: !parquet-tools head /tmp/test.parquet                                                                          
a = 1577836800000000

如上所示,pandas-1.0.5 将时间戳类型转换为TIMESTAMP_MILLIS,而pandas-1.1.2 将其转换为TIMESTAMP_MICROS

我正在使用pandas-1.1.2,但我需要类型为TIMESTAMP_MILLIS 用于parquet 文件的下游消费(由Presto 查询),请问该怎么做?

我正在使用pyarrow 引擎。

【问题讨论】:

    标签: python pandas parquet


    【解决方案1】:

    这可以通过pyarrow 进行配置,幸运的是pd.to_parquet 将任何未知的 kwrgs 发送到 parquet 库。
    看着pyarrow docs for ParquetWriter我们发现

    coerce_timestamps (str, default None) – 为特定分辨率添加时间戳。默认值取决于版本。对于 version='1.0'(默认),纳秒将转换为微秒('us'),秒转换为毫秒('ms')。对于 version='2.0',保留原始分辨率,默认情况下不进行转换。强制转换可能会导致数据丢失,在这种情况下,allow_truncated_timestamps=True 可用于抑制引发的异常。有效值:{None, ‘ms’, ‘us’}

    这意味着您可以将时间戳强制设置为毫秒

    df.to_parquet(path, coerce_timestamps="ms")
    

    或微秒

    df.to_parquet(path, coerce_timestamps="us")
    

    这使它成为您需要的代码

    pd.DataFrame([pd.Timestamp('2020-01-01')], columns=['a']).to_parquet('/tmp/test.parquet', coerce_timestamps="ms")
    

    也要注意这部分文档

    allow_truncated_timestamps=True 可用于抑制引发的异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      • 2019-09-20
      • 2017-05-05
      • 2014-02-25
      • 2016-02-21
      相关资源
      最近更新 更多