Polars:使用设置的模式将列添加到空数据框中

问题描述 投票:0回答:3

我创建了一个具有设定架构的空数据框。架构设置列的数据类型。我想将单个名称匹配列(系列)添加到空数据框中。但好像不太喜欢。

# Empty dataframe with a given schema    
df = pl.DataFrame(schema={"my_string_col":str, "my_int_col": int, "my_bool_col": bool})

# Now I try to add a series to it
df = df.with_columns(pl.Series(name="my_int_col", values=[1, 2, 3, 4, 5]))

但是我收到以下错误:

exceptions.ShapeError: unable to add a column of length 5 to a dataframe of height 0

Polars 似乎无法用空值填充其余列(即 my_string_col 和 my_bool_col)。在 Pandas 中,你可以通过多种方式做到这一点,我想知道我是否遗漏了一些东西或者还没有实现?

python python-polars
3个回答
5
投票

这本质上是一个

.join
操作

col = pl.Series(name="my_int_col", values=[1, 2, 3, 4, 5])

df.join(col.to_frame(), on=col.name, how="outer")
shape: (5, 3)
┌───────────────┬────────────┬─────────────┐
│ my_string_col ┆ my_int_col ┆ my_bool_col │
│ ---           ┆ ---        ┆ ---         │
│ str           ┆ i64        ┆ bool        │
╞═══════════════╪════════════╪═════════════╡
│ null          ┆ 1          ┆ null        │
│ null          ┆ 2          ┆ null        │
│ null          ┆ 3          ┆ null        │
│ null          ┆ 4          ┆ null        │
│ null          ┆ 5          ┆ null        │
└───────────────┴────────────┴─────────────┘

0
投票

您正在尝试将包含 5 个元素的系列添加到包含 0 行的空 DataFrame 中。

    import polars as pl

df_new = pl.DataFrame({
    "my_string_col": [None],
    "my_int_col": [1],
    "my_bool_col": [None]
})

dfs = [df_new] * 5

df = pl.concat(dfs)

print(df)

输出:

shape: (5, 3)
┌───────────────┬────────────┬─────────────┐
│ my_string_col ┆ my_int_col ┆ my_bool_col │
│ ---           ┆ ---        ┆ ---         │
│ f64           ┆ i64        ┆ f64         │
╞═══════════════╪════════════╪═════════════╡
│ null          ┆ 1          ┆ null        │
│ null          ┆ 1          ┆ null        │
│ null          ┆ 1          ┆ null        │
│ null          ┆ 1          ┆ null        │
│ null          ┆ 1          ┆ null        │
└───────────────┴────────────┴─────────────┘

0
投票

这也可以被视为数据帧的“对角串联”。来自 how

pl.concatenate
 参数的文档:

对角线:查找列模式之间的并集并用 null 填充缺失的列值。

import polars as pl df = pl.DataFrame(schema={"my_string_col":str, "my_int_col": int, "my_bool_col": bool}) series = pl.Series(name="my_int_col", values=[1, 2, 3, 4, 5]) pl.concat([df, series.to_frame()], how="diagonal")
shape: (5, 3)
┌───────────────┬────────────┬─────────────┐
│ my_string_col ┆ my_int_col ┆ my_bool_col │
│ ---           ┆ ---        ┆ ---         │
│ str           ┆ i64        ┆ bool        │
╞═══════════════╪════════════╪═════════════╡
│ null          ┆ 1          ┆ null        │
│ null          ┆ 2          ┆ null        │
│ null          ┆ 3          ┆ null        │
│ null          ┆ 4          ┆ null        │
│ null          ┆ 5          ┆ null        │
└───────────────┴────────────┴─────────────┘
© www.soinside.com 2019 - 2024. All rights reserved.