You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何动态选取Polars DataFrame的最后一列?

在Polars中动态选取最后一列的方法

针对你提供的Polars DataFrame(版本0.18.3),以下几种方法可以实现类似Pandas中df.iloc[:,-1:]的效果,动态选取最后一列:

方法1:使用负索引列选择(推荐)

Polars支持直接通过负索引指定列,pl.col(-1)代表最后一列,结合select()方法即可返回包含最后一列的DataFrame:

import polars as pl

df = pl.DataFrame({
    "col1": [1, 2],
    "col2": ["2", "3"],
    "col3": [3, 4]
})

# 选取最后一列(返回DataFrame)
last_col_df = df.select(pl.col(-1))
print(last_col_df)

输出结果:

shape: (2, 1)
┌──────┐
│ col3 │
│ ---  │
│ i64  │
╞══════╡
│ 3    │
│ 4    │
└──────┘

方法2:获取最后一列的Series

如果需要返回Series而非DataFrame,可以使用to_series()方法:

last_col_series = df.to_series(-1)
print(last_col_series)

输出结果:

shape: (2,)
Series: 'col3' [i64]
[
        3
        4
]

方法3:通过列名列表选取

先获取所有列名,再选取最后一个列名进行筛选:

last_col_df = df.select(df.columns[-1])

内容的提问来源于stack exchange,提问作者user459872

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 18:30:18