提问人:Sudoh 提问时间:11/8/2023 最后编辑:Sudoh 更新时间:11/9/2023 访问量:86
如何在特定索引处插入 polars.lit(“some_string”)?
How to insert a polars.lit("some_string") at a specific index?
问:
在polars
其中 is adt
dataFrame
dt.with_columns(
new_column = pl.lit('some_text')
)
将添加一个名为new_column
some_text
和
dt.insert_at_idx(index:int, series:series)
将在给定索引处插入series
但是有没有办法将这两个任务结合起来,即在特定索引处添加一个。pl.lit()
我试过了
dt.insert_at_idx(index:int, pl.lit("some_text"))
但这没有用。
有谁知道如何在指定的索引上?pl.lit()
答:
2赞
Dean MacGregor
11/8/2023
#1
我会先创建一个现有列的列表,然后使用 将新列作为表达式添加到该列表中,最后使用 以该顺序获取列。.insert
select
一次性方法
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。
评论
pl.insert_at_idx
DataFrame.insert_at_idx
pl.DataFrame.insert_at_idx
pl.insert_at_idx
AttributeError: module 'polars' has no attribute 'insert_at_idx'