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

如何使用字符串列表对Pandas DataFrame的列进行排序

Absolutely! This is one of the most common and straightforward ways to reorder columns in a Pandas DataFrame. First, a quick note: your initial list syntax has a small error—list('ad','gf','hl','bc') won't work (the list() constructor only takes one argument). You'll want to define your target column order as a regular Python list:

str_list = ['ad','gf','hl','bc']

Core Solution

Once you have your target list set up, you can directly use it to index your DataFrame's columns. This will rearrange the columns exactly to match the order in str_list:

# Reorder columns to match str_list
df_reordered = df[str_list]

Full Working Example

Here's a complete, runnable example to see this in action:

import pandas as pd

# Create a DataFrame with randomly ordered columns
df = pd.DataFrame({
    'gf': [1, 2, 3],
    'bc': [4, 5, 6],
    'ad': [7, 8, 9],
    'hl': [10, 11, 12]
})

# Target column order
str_list = ['ad','gf','hl','bc']

# Reorder the columns
df_reordered = df[str_list]

# Verify the new column order
print("Original columns:", df.columns.tolist())
print("Reordered columns:", df_reordered.columns.tolist())

Robustness Tip

If your str_list might contain columns that don't exist in your DataFrame, you'll get a KeyError if you try the direct approach. To avoid this, filter the list to only include columns that are actually present in the DataFrame:

# Filter to valid columns only
valid_columns = [col for col in str_list if col in df.columns]
df_reordered = df[valid_columns]

# Optional: Check for missing columns
missing_columns = [col for col in str_list if col not in df.columns]
if missing_columns:
    print(f"Warning: These columns are missing from the DataFrame: {missing_columns}")

That's all there is to it—this method is efficient, readable, and the standard way to handle column reordering in Pandas!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:48:49