在Python中进行数据分析时,你首先会学到的一件事是处理列表是缓慢的。
因此,你可能会对Polars中的pl.List数据类型保持警惕。
但你不必担心——这个数据类型是某些快速并行分析的核心。
在List列中,每一行都是一个Polars序列(Series)。并且每个序列都有相同的数据类型(dtype)。
在这里,我们创建了一个包含两个列表列的数据框(DataFrame):整数、浮点数。类型是从第一个元素推断出来的。
import polars as pl
dfLists=pl.DataFrame({
'ints':[[0,1],[2,3]],
'floats':[[0.0,1],[2,3]],},
schema={"ints": pl.Array(pl.Int64, 2),
"floats": pl.Array(pl.Float64, 2),},
)
print(dfLists)
shape: (2, 2)
┌───────────────┬───────────────┐
│ ints ┆ floats │
│ --- ┆ --- │
│ array[i64, 2] ┆ array[f64, 2] │
╞═══════════════╪═══════════════╡
│ [0, 1] ┆ [0.0, 1.0] │
│ [2, 3] ┆ [2.0, 3.0] │
└───────────────┴───────────────┘
做一些分析
List数据类型的优点在于,你可以很容易地对每一行上的序列(Series)执行相同的分析。
import polars as pl
dfLists=pl.DataFrame({
'ints':[[0,1],[2,3]],
'floats':[[0.0,1],[2,3]],},
schema={"ints": pl.Array(pl.Int64, 2),
"floats": pl.Array(pl.Float64, 2),},
)
print(dfLists.select(pl.all().arr.max()))
shape: (2, 2)
┌──────┬────────┐
│ ints ┆ floats │
│ --- ┆ --- │
│ i64 ┆ f64 │
╞══════╪════════╡
│ 1 ┆ 1.0 │
│ 3 ┆ 3.0 │
└──────┴────────┘
这是一个简单的例子,但你可以根据需要让它变得复杂(如果你想要的话,它可以并行处理)。
尽管我们使用Python列表创建了它们,但它们实际上是快速的序列(Series)。
混合使用它们呢?
如果我们传递一个包含混合类型的列表会发生什么?
在这种情况下,该列将具有pl.Object数据类型。
dfMixed = pl.DataFrame({
'ints':[ [0,1], [2,3]],
'mixed':[ ['a',0],['b',1]]
})
print(dfMixed)
shape: (2, 2)
┌───────────┬──────────┐
│ ints ┆ mixed │
│ --- ┆ --- │
│ list[i64] ┆ object │
╞═══════════╪══════════╡
│ [0, 1] ┆ ['a', 0] │
│ [2, 3] ┆ ['b', 1] │
└───────────┴──────────┘
在pl.Object数据类型的每一行中,实际上只是一个Python列表。虽然它们可以包含任意对象,但这些Object列对于分析来说并不那么高效。
总的来说,要小心使用列表(也许也要小心pl.Object),但不要害怕pl.Lists!