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

如何基于指定列表对Pandas DataFrame的行进行自定义排序?

Sorting a DataFrame by a Custom List Order

Got it, let's solve this problem where you need to sort your DataFrame rows to match the exact order of a given list. Using your example data:

import pandas as pd
df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'], 'income': [40000, 50000, 42000]})
z = ["Jane", "Alice", "Bob"]

We have two straightforward methods to get the desired sorted DataFrame:

Method 1: Using Categorical Data Type

This method is great because it explicitly defines the order you want, and works even if there are duplicates in your DataFrame (though your problem states each value appears once). Here's how:

  1. Convert the user column to a Categorical type, specifying your custom list as the ordered categories:
df['user'] = pd.Categorical(df['user'], categories=z, ordered=True)
  1. Now sort the DataFrame by the user column—pandas will respect the custom order you set:
df_sorted = df.sort_values('user')
  1. (Optional) If you don't want to keep the user column as a Categorical type, convert it back to a regular string:
df_sorted['user'] = df_sorted['user'].astype(str)

The resulting df_sorted will look like this:

userincome
Jane50000
Alice42000
Bob40000

Method 2: Using set_index + reindex

Since your list z contains exactly the values from the user column (each once), you can reindex the DataFrame directly:

  1. Set the user column as the index of the DataFrame:
df_indexed = df.set_index('user')
  1. Reindex the DataFrame using your custom list z—this will reorder the rows to match the list:
df_sorted = df_indexed.reindex(z).reset_index()

This achieves the same result as Method 1, and is a bit more concise if you know all values in z exist in the DataFrame.

Both methods work perfectly for your use case—pick whichever feels more intuitive to you!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 15:22:45