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

如何基于Year行数据对Polars DataFrame列排序并保留region列首位?

基于Polars中指定行的数值对列排序(保留首列)

要实现基于Year行的数值对列排序且固定region列在首位,你需要先提取目标行的排序依据,再重新指定列的顺序,具体步骤如下:

步骤1:提取Year行的列值并确定排序后的列顺序

先筛选出region为Year的行,提取除region外的列及其对应数值,然后按数值升序排列这些列名:

import polars as pl

df = pl.DataFrame({
    'region': ['EU', 'ASIA', 'AMER', 'Year'],
    'Share': [99, 6, -30, 2020],
    'Ration': [70, 4, -10, 2019],
    'Lots': [70, 4, -10, 2018],
    'Stake': [80, 5, -20, 2021],
})

# 获取Year行的数值,排除region列
year_row = df.filter(pl.col('region') == 'Year').select(pl.exclude('region')).to_dict(as_series=False)
# 按数值升序排序列名
sorted_cols = sorted(year_row.keys(), key=lambda x: year_row[x][0])

步骤2:重新选择列,固定region在首位

将region列放在最前面,拼接排序后的列名列表,用select方法重排列:

# 构造最终列顺序:region + 排序后的列
final_cols = ['region'] + sorted_cols
# 重新选择列得到结果
result_df = df.select(final_cols)
print(result_df)

执行后输出结果如下,完全符合需求:

shape: (4, 5)
┌────────┬──────┬────────┬───────┬───────┐
│ region ┆ Lots ┆ Ration ┆ Share ┆ Stake │
│ ---    ┆ ---  ┆ ---    ┆ ---   ┆ ---   │
│ str    ┆ i64  ┆ i64    ┆ i64   ┆ i64   │
╞════════╪══════╪════════╪═══════╪═══════╡
│ EU     ┆ 70   ┆ 70     ┆ 99    ┆ 80    │
│ ASIA   ┆ 4    ┆ 4      ┆ 6     ┆ 5     │
│ AMER   ┆ -10  ┆ -10    ┆ -30   ┆ -20   │
│ Year   ┆ 2018 ┆ 2019   ┆ 2020  ┆ 2021  │
└────────┴──────┴────────┴───────┴───────┘

补充说明

Polars的sort方法默认是对行进行排序,而你需要的是对列重排,因此不能直接用sort。通过提取目标行的数值作为排序依据,再手动构造列顺序并重新选择,是实现这类需求的标准思路。

内容的提问来源于stack exchange,提问作者Phil-ZXX

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 22:47:07