每张行情表里有两列需要特殊处理,二者都关乎“明确”。股票代码会重复几千次,把它的文本存在每一行里是浪费。时间戳看起来是一个东西,其实是整数加单位,有时还要加时区,混淆它们会让成交偏移几个小时,或者差上一千倍。Arrow 为这两者各有一个类型,了解它们可以避免数据工作中一些代价最高的隐性错误。
用通俗的话说这个想法
我们在哪里。 主题 4 说明字符串列要为每一行付偏移量和字符的开销。这里给出对策,与 Parquet 的字典编码是同一个思路:每个不同的值只保留一份。时间戳这一半为综合项目做准备,那里的 tick 带有真实时间。最后两个主题则在进程之间移动数据。
由两部分组成的数组:一个字典,每个不同的值只存一份;以及一列小整数索引,每行一个,指向字典。读取一行就是用它的索引去字典里查。
重复文本只存一次
dictionary_encode 就地把字符串列换成字典列。字典按首次出现的顺序存放五个代码,每一行变成一个 4 字节的索引。读回的值完全相同,所以只看值的代码毫无察觉,而这一列在这里少占约 40% 的字节,字符串越长、不同值越少,节省越多。
# Dictionary-encode the symbol column and compare its sizecoded = dictionary_encode(table, "symbol")print(coded.schema.field("symbol").type)print("bytes:", f"{table['symbol'].nbytes:,}", "->", f"{coded['symbol'].nbytes:,}")values, indices = dictionary_parts(coded["symbol"].chunk(0))print("dictionary:", values)print("first indices:", indices[:5], "| values read back the same:", coded["symbol"].to_pylist() == table["symbol"].to_pylist())
dictionary<values=string, indices=int32, ordered=0> bytes: 234,451 -> 134,147 dictionary: ['AAPL', 'JPM', 'XOM', 'JNJ', 'KO'] first indices: [0, 0, 0, 0, 0] | values read back the same: True
时间戳是带单位的整数
行情里的是 date32:自 1970 年起的天数。日内系统需要真正的时刻,所以 as_utc_timestamps 把每个日期转换成你选定单位下的 UTC 午夜。timestamp_ints 展示实际存储的内容:自 1970-01-01 起的单位数。同一时刻以秒计是 946,857,600,以毫秒计是 946,857,600,000,这就是为什么用错误单位读取列会得到 1970 年或 5 万年的日期。
# Midnight UTC for the first bar, in four units: the same instant, four different integersfor unit in ("s", "ms", "us", "ns"): stamped = as_utc_timestamps(table, "date", unit) print(f"{str(stamped.schema.field('date').type):28} {timestamp_ints(stamped['date'].chunk(0))[0]:>22,}")
timestamp[s, tz=UTC] 946,857,600 timestamp[ms, tz=UTC] 946,857,600,000 timestamp[us, tz=UTC] 946,857,600,000,000 timestamp[ns, tz=UTC] 946,857,600,000,000,000
timestamp[ms, tz=UTC] 与 timestamp[ms] 存储的是同一个整数;时区只影响显示以及本地日期的计算。成交时间以 UTC 存储,在边界处再转换。像日线这样只有日期的值保持 date32,不要改成午夜时间戳,除非某个系统需要时刻。
任务要求
- 1`dictionary_encode` 与 `dictionary_parts`
table.set_column(index, name, pc.dictionary_encode(column));对字典数组用array.dictionary和array.indices。 - 2`as_utc_timestamps` 与 `timestamp_ints`
column.cast(pa.timestamp(unit, tz="UTC"))和set_column;array.cast(pa.int64())可看到底层整数。
实验:评分内容
4 个任务 · 100 分- 重复文本只存一次:
dictionary_encode25 分 - 拆开它:
dictionary_parts25 分 - 日期转 UTC 时间戳:
as_utc_timestamps25 分 - 时间背后的整数:
timestamp_ints25 分