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

如何基于另一pandas DataFrame的列排序结果对目标DataFrame按列排序?

问题

我有两个结构完全一致(索引、列数均相同)的pandas DataFrame:一个存储相似词汇,另一个存储对应的相似度得分。我需要对相似度得分DataFrame按列排序(使用sort_values方法,axis=1),并将相同的排序规则同步应用到词汇DataFrame上。

原始数据

词汇DataFrame:

indexCol 0Col 1Col 2
TrainsRocketsCarsShips
PaintingsCanvasesPaintInk
GermsInfectionsDirtDust

相似度得分DataFrame:

indexCol 0Col 1Col 2
Trains478033
Paintings229030
Germs774052

期望结果

排序后的词汇DataFrame(按照得分DataFrame的降序排序规则):

indexCol 0Col 1Col 2
TrainsCarsRocketsShips
PaintingsPaintCanvasesInk
GermsInfectionsDustDirt

解决方案

核心思路是先获取得分DataFrame排序后的列索引顺序,再用这个顺序重新排列词汇DataFrame的列。

代码实现

import pandas as pd

# 构建原始DataFrame
# 词汇DataFrame
vocab_df = pd.DataFrame(
    {
        "Col 0": ["Rockets", "Canvases", "Infections"],
        "Col 1": ["Cars", "Paint", "Dirt"],
        "Col 2": ["Ships", "Ink", "Dust"]
    },
    index=["Trains", "Paintings", "Germs"]
)

# 相似度得分DataFrame
score_df = pd.DataFrame(
    {
        "Col 0": [47, 22, 77],
        "Col 1": [80, 90, 40],
        "Col 2": [33, 30, 52]
    },
    index=["Trains", "Paintings", "Germs"]
)

# 对得分DataFrame按行降序排序,获取每一行的列排序索引
sorted_indices = score_df.apply(lambda x: x.sort_values(ascending=False).index, axis=1)

# 根据排序索引重新排列词汇DataFrame的每一行
sorted_vocab_df = vocab_df.apply(lambda x: x.reindex(sorted_indices.loc[x.name]), axis=1)

print(sorted_vocab_df)

代码解释

  1. 获取排序索引:使用apply遍历得分DataFrame的每一行,对每行的值降序排序后提取对应的列索引,得到每行的专属排序规则。
  2. 同步排序词汇DataFrame:同样用apply遍历词汇DataFrame的每一行,根据该行对应的排序索引重新排列列的顺序,实现和得分DataFrame的完全同步排序。

如果需要升序排序,只需将sort_values的ascending参数改为True即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 14:38:23