【问题标题】:Polars - Select columns not exist with no errorPolars - 选择列不存在且没有错误
【发布时间】:2023-01-19 23:26:21
【问题描述】:

是否可以毫无例外地从 polars 数据框中选择可能不存在的列(返回具有默认值或 null/None 的列)?

我真正想要的行为可以在示例中显示如下:

import polars as pl

df1 = pl.DataFrame({"id": [1, 2, 3], "bar": ["sugar", "ham", "spam"]})
df2 = pl.DataFrame({"id": [4, 5, 6], "other": ["a", "b", "b"]})

df1.write_csv("df1.csv")
df2.write_csv("df2.csv")

df = pl.scan_csv("df*.csv").select(["id", "bar"])
res = df.collect()

现在,如果我运行上面的代码,将会出现错误,因为df2.csv文件不包含专栏“酒吧”.我想要的结果是——资源只是里面的内容df1.csv,这意味着数据框在df2.csv文件由于没有列将不会被选中“酒吧”在里面。

【问题讨论】:

  • 除了将“df*.csv”更改为“df1.csv”,我认为这不是您想要的,不支持。您可以在写入文件时将缺失的列添加为空值吗?

标签: python python-polars


【解决方案1】:

我的意思是在上面提到的评论中,这个功能在极地中不存在,但我们可以构建一个可以满足您需求的功能

import glob

def scan_csv_with_columns(file: str, needed_colnames: list[str]) -> pl.LazyFrame:
    file_collector = []
    for filename in glob.glob(file):
        df_scan = pl.scan_csv(filename)
        if (df_scan.columns == needed_colnames):
            file_collector.append(df_scan)
    df = pl.concat(file_collector, how="vertical")
    return(df)

file = "df*.csv"
needed_colnames = ["id", "bar"]
df = scan_csv_with_columns(file, needed_colnames)
df.collect()

shape: (3, 2)
┌─────┬───────┐
│ id  ┆ bar   │
│ --- ┆ ---   │
│ i64 ┆ str   │
╞═════╪═══════╡
│ 1   ┆ sugar │
│ 2   ┆ ham   │
│ 3   ┆ spam  │
└─────┴───────┘

【讨论】:

    猜你喜欢
    • 2019-03-07
    • 1970-01-01
    • 2015-12-30
    • 2015-01-05
    • 1970-01-01
    • 2020-03-10
    • 2016-12-27
    • 2016-02-23
    • 2021-06-07
    相关资源
    最近更新 更多