如何在特定索引处插入 polars.lit(“some_string”)?

How to insert a polars.lit("some_string") at a specific index?

提问人:Sudoh 提问时间:11/8/2023 最后编辑:Sudoh 更新时间:11/9/2023 访问量:86

问:

polars

其中 is adtdataFrame

dt.with_columns(
    new_column = pl.lit('some_text')
)

将添加一个名为new_columnsome_text

dt.insert_at_idx(index:int, series:series)

将在给定索引处插入series

但是有没有办法将这两个任务结合起来,即在特定索引处添加一个。pl.lit()

我试过了

dt.insert_at_idx(index:int, pl.lit("some_text"))

但这没有用。

有谁知道如何在指定的索引上?pl.lit()

蟒蛇极地

评论

1赞 jqurious 11/8/2023
你能展示一个输入/输出的实际例子吗?
0赞 Sudoh 11/8/2023
@jqurious 我正在处理 1.13 亿行(是的,那是 1.13 亿行)。我可以做一个假桌子,但这怎么会比帖子中已有的更好呢?这篇文章描述了一个“问题”,并为您提供了重新创建它并解决它所需的一切,如果存在这样的解决方案。这是一个问题,因为缺乏容易发现的问题是一个问题。
1赞 jqurious 11/8/2023
问题是不存在的,所以不清楚你是在谈论行索引还是列索引。我遇到的下一个问题是,如果是列索引 - 如果索引太大,是否应该添加空列来填充?但后来我意识到你所指的方法是,它有索引长度限制。pl.insert_at_idxDataFrame.insert_at_idx
0赞 Sudoh 11/8/2023
@jqurious.insert_at_idx
1赞 jqurious 11/9/2023
是的,谢谢。但是该方法的名称只是您的问题所指的。.pl.DataFrame.insert_at_idxpl.insert_at_idxAttributeError: module 'polars' has no attribute 'insert_at_idx'

答:

2赞 Dean MacGregor 11/8/2023 #1

我会先创建一个现有列的列表,然后使用 将新列作为表达式添加到该列表中,最后使用 以该顺序获取列。.insertselect

一次性方法

df = pl.DataFrame(data={'a':[1,2,3], 'b':[2,3,4], 'c':[3,4,5]})
cols=df.columns
cols.insert(2, pl.lit('some_text').alias("newcol"))
df=df.select(cols)
df
shape: (3, 4)
┌─────┬─────┬───────────┬─────┐
│ a   ┆ b   ┆ newcol    ┆ c   │
│ --- ┆ --- ┆ ---       ┆ --- │
│ i64 ┆ i64 ┆ str       ┆ i64 │
╞═════╪═════╪═══════════╪═════╡
│ 1   ┆ 2   ┆ some_text ┆ 3   │
│ 2   ┆ 3   ┆ some_text ┆ 4   │
│ 3   ┆ 4   ┆ some_text ┆ 5   │
└─────┴─────┴───────────┴─────┘

我认为修改 df 的方法可能会在某个时候被弃用,因此最好不要使用它们,或者至少不要指望它们。我什至不确定是否还有其他人。您可以使用自定义函数(例如)快捷方式执行上述内容:

功能方法

def with_at_idx(df, index, *args, **kwargs):
    if len(args)+len(kwargs)>1:
        raise ValueError("Only one new column allowed")
    # You could, of course, take out this error and the for 
    # loops will continue to work but then you need to deal 
    # with precedent between args and kwargs
    cols=df.columns
    for arg in args:
        cols.insert(index, arg)
    for colname, arg in kwargs.items():
        cols.insert(index, arg.alias(colname))
    return df.select(cols)
pl.DataFrame.with_at_idx=with_at_idx

然后你可以做:

df.with_at_idx(2, new_column=pl.lit(5))
shape: (3, 4)
┌─────┬─────┬────────────┬─────┐
│ a   ┆ b   ┆ new_column ┆ c   │
│ --- ┆ --- ┆ ---        ┆ --- │
│ i64 ┆ i64 ┆ i32        ┆ i64 │
╞═════╪═════╪════════════╪═════╡
│ 1   ┆ 2   ┆ 5          ┆ 3   │
│ 2   ┆ 3   ┆ 5          ┆ 4   │
│ 3   ┆ 4   ┆ 5          ┆ 5   │
└─────┴─────┴────────────┴─────┘

df.with_at_idx(1, pl.lit("some_text").alias("newcol"))
shape: (3, 4)
┌─────┬───────────┬─────┬─────┐
│ a   ┆ newcol    ┆ b   ┆ c   │
│ --- ┆ ---       ┆ --- ┆ --- │
│ i64 ┆ str       ┆ i64 ┆ i64 │
╞═════╪═══════════╪═════╪═════╡
│ 1   ┆ some_text ┆ 2   ┆ 3   │
│ 2   ┆ some_text ┆ 3   ┆ 4   │
│ 3   ┆ some_text ┆ 4   ┆ 5   │
└─────┴───────────┴─────┴─────┘

这不会修改 df 就地,因此您需要这样做

df=df.with_at_idx(...)修改基础 DF。