几乎每项量化任务都以同样的方式开始:一个价格文件,以及在做任何别的事之前先看一眼的需要。有多少行?有哪些列,什么类型?日期是真的日期还是只是文本?Polars 用一行代码回答每个问题,即使文件有几百万行也很快,因为表是按列存放在 Arrow 内存中的。
用通俗的话说这个想法
我们在哪里。 Polars 技能的第一个主题,初级难度,只需要 Python。后面的主题会用表达式变换列、按组汇总、连接表并处理时间。如果你了解 pandas,会发现思路相同而风格不同:列的类型严格,没有行索引,工作是用表达式描述的,而不是逐个单元格操作。
由具名列组成的表,每列只含一种类型的值,所有列等长。在 Polars 中,列是 Arrow 数组,没有行索引,单独的一列称为 Series。
读取文件并查看
pl.read_csv(path, try_parse_dates=True) 读取文件,并把看起来像日期的文本变成真正的 Date 值,后面的主题才能按月分组或按时间连接。没有这个参数,列会保持为文本,所有与日期相关的操作都会悄悄失败。describe_frame 汇总形状和每列类型,这是对任何新文件最先要检查的内容。
# The shape and the type of every column of the bars tablerows, columns, fields = describe_frame(df)print(rows, "rows,", columns, "columns")for name, dtype in fields: print(f"{name:8} {dtype}")
33493 rows, 7 columns symbol String date Date open Float64 high Float64 low Float64 close Float64 volume Int64
# Write KO's rows to a CSV and read them back with the dates parseddf.filter(pl.col("symbol") == "KO").write_csv("ko_copy.csv")ko = read_bars_file("ko_copy.csv")print(ko.shape, "| date column type:", ko.schema["date"])print(pl.read_csv("ko_copy.csv").schema["date"], "<- without try_parse_dates")
(6699, 7) | date column type: Date String <- without try_parse_dates
查看行并汇总一列
head_rows 把前几行作为元组展示,每列一个值,是判断数据是否正常的最快方式。column_summary 取一列(一个 Series),询问它的最小值、最大值、平均值和空值个数。这些是列自身的方法,在编译代码中对整列一次算完。最小、最大和平均会跳过空值,所以空值个数告诉你缺了多少个值。
# The first two rows, and a summary of the closing pricesfor row in head_rows(df, 2): print(row)summary = column_summary(df, "close")print({key: round(value, 3) if isinstance(value, float) else value for key, value in summary.items()})
('AAPL', datetime.date(2000, 1, 3), 0.785568, 0.842382, 0.761624, 0.83826, 638640787)
('AAPL', datetime.date(2000, 1, 4), 0.810884, 0.828742, 0.758094, 0.76771, 610726329)
{'min': 0.197, 'max': 365.18, 'mean': 61.862, 'nulls': 0}价格列因为某个单元格里有短横线而变成 String,或成交量因为一个多余的小数点变成 Float64,就不会表现得像你期望的数字,错误要到很晚才暴露。先看每个新文件的模式。在 Polars 中,一列绝不会混合类型,所以类型不对是关于数据的信号,不能忽略。
任务要求
- 1`read_bars_file`
pl.read_csv(path, try_parse_dates=True)。 - 2`describe_frame` 与 `head_rows`
df.shape,配合str(dtype)的df.schema.items();df.head(n).rows()。 - 3`column_summary`
df[column]是一个 Series:.min()、.max()、.mean()、.null_count()。
pl.read_csv("bars.csv") 后,df.schema["date"] 显示 String。怎么修复?实验:评分内容
4 个任务 · 100 分- 读取带日期的 CSV:
read_bars_file25 分 - 形状与类型:
describe_frame25 分 - 前几行:
head_rows25 分 - 汇总一列:
column_summary25 分