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

如何用Pandas同时按列索引和列头提取多Excel文件数据?

Solution for Combining Index-based and Name-based Column Selection in Pandas

Absolutely, you can pull off this mix of column selection! The usecols parameter does only accept a single type (either all indices or all names), but we can work around that with two straightforward approaches depending on your file size and performance needs.


Method 1: Efficient Column Name Pre-fetch (Best for Large Files)

This approach first grabs the name of the first column (since its index is fixed at 0 but name varies), then combines it with your fixed column names to use in usecols. This avoids loading unnecessary data into memory.

import pandas as pd

def load_target_columns(file_path):
    # Step 1: Read only the header row to get column names (no data rows)
    header_only = pd.read_excel(file_path, nrows=0)
    
    # Step 2: Get the name of the first column (index 0)
    first_col_name = header_only.columns[0]
    
    # Step 3: Combine with your fixed column names
    desired_columns = [first_col_name, 'TOTAL', 'CLEAR', 'NON-CLEAR', 'SYSTEM']
    
    # Optional: Validate all fixed columns exist in the file
    fixed_cols = ['TOTAL', 'CLEAR', 'NON-CLEAR', 'SYSTEM']
    missing_cols = [col for col in fixed_cols if col not in header_only.columns]
    if missing_cols:
        print(f"Warning: File {file_path} is missing columns: {', '.join(missing_cols)}")
        # Add handling here (e.g., skip file, proceed with available columns)
    
    # Step 4: Load only the desired columns
    df = pd.read_excel(file_path, usecols=desired_columns)
    return df

# Example usage
your_file = "sample_data.xlsx"
result_df = load_target_columns(your_file)

Method 2: Full Load + Column Filter (Simpler for Small Files)

If your Excel files are small enough that loading all columns isn't an issue, you can read the entire file first, then filter down to the columns you need—combining index-based selection for the first column and name-based selection for the rest.

import pandas as pd

def load_target_columns_simple(file_path):
    # Step 1: Read the entire file
    full_df = pd.read_excel(file_path)
    
    # Step 2: Combine the first column (by index) and fixed columns (by name)
    target_df = full_df[[full_df.columns[0], 'TOTAL', 'CLEAR', 'NON-CLEAR', 'SYSTEM']]
    
    return target_df

# Example usage
your_file = "sample_data.xlsx"
result_df = load_target_columns_simple(your_file)

This method is more readable for quick scripts, just keep in mind it uses more memory for large datasets.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 11:57:46