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

Polars中如何通过列名选择连续列范围?

Polars中按列名范围选取列的方法
  • 使用pl.col()的through()方法,这是和Pandas列名范围切片最直接的等效方式,无需逐一罗列列名:

    import polars as pl
    
    # 示例DataFrame
    df = pl.DataFrame({
        "id": [1, 2, 3],
        "first_name": ["Alice", "Bob", "Charlie"],
        "middle_name": ["Marie", "James", "David"],
        "last_name": ["Smith", "Johnson", "Brown"],
        "age": [25, 30, 35]
    })
    
    # 选取first_name到last_name之间的所有列(包含两端)
    selected_df = df.select(pl.col("first_name").through("last_name"))
    print(selected_df)
    

    执行后会返回包含first_name、middle_name、last_name的子DataFrame,和Pandas中df.loc[:, 'first_name':'last_name']的结果一致。

  • 若需要更灵活的范围调整,可通过列名列表切片实现:

    cols = df.columns
    start_idx = cols.index("first_name")
    end_idx = cols.index("last_name") + 1  # 切片左闭右开,需+1包含结束列
    selected_df = df.select(cols[start_idx:end_idx])
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 16:24:51