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

Python中从CSV文件筛选匹配输入值的指定列数据及修正长度判断错误的技术问询

Fixes for Your CSV Matching Code

Let’s work through both of your issues step by step to get your code working exactly as you need:

1. Print Only Specified Columns

Instead of returning the entire matching row(s), you can explicitly select the columns you want using pandas' indexing. You have two straightforward options:

  • Use column names (more readable, recommended if you know the exact labels in your CSV):
    result = file.loc[file['Column 2'] == codeNum, ['Column 4', 'Column 5']]
  • Use position-based indexing (if you only know column positions—remember pandas uses 0-based indexing, so 3 = 4th column, 4 = 5th column):
    result = file.loc[file['Column 2'] == codeNum, file.columns[[3, 4]]]

Printing result after this will only show the columns you specified, not the entire row.

2. Fix Length Validation & Exact Matching Issues

Your current code has two key problems here:

  • Length check logic: Your condition len(str(codeNum)) >3 and len(str(codeNum)) <15 excludes values with exactly 3 or 15 characters. Since your requirement is 3–15 characters (inclusive), adjust it to >=3 and <=15.
  • Substring vs exact match: str.contains() returns any row where your input appears anywhere in Column 2 (e.g., input "100" will match "1000" or "2100"). For precise matches, use exact equality (==) instead.
  • Input format preservation: Converting input to int strips leading zeros (e.g., "0100" becomes 100, which changes its length from 4 to 3). If your codes might have leading zeros, keep the input as a string.

Revised Full Code

Here’s the updated code with all fixes applied:

import pandas as pd

# Load your CSV file
file = pd.read_csv('filename.csv', encoding="ISO-8859-1", engine='python', sep=';')

def codechoice():
    # Keep input as string to preserve leading zeros and accurate length measurement
    codeNum = input("What's the code: ").strip()
    
    # Validate code length (3 to 15 characters inclusive)
    if 3 <= len(codeNum) <= 15:
        # Filter rows where Column 2 exactly matches the input, then select Column 4 and 5
        # Adjust column names to match your actual CSV labels
        result = file.loc[file['Column 2'] == codeNum, ['Column 4', 'Column 5']]
        
        # Handle cases where no matches are found
        if result.empty:
            print("No matching rows found for that code.")
        else:
            print(result)
    else:
        print("Error: Code must be between 3 and 15 characters long.")

codechoice()

Key Changes Breakdown:

  • Input handling: Removed int() conversion to keep the input as a string, ensuring leading zeros stay intact and length is measured correctly.
  • Length validation: Updated the condition to include boundary values (3 and 15 characters) as required.
  • Exact matching: Replaced str.contains() with direct equality check to avoid unintended substring matches.
  • Targeted columns: Used loc to filter rows and select only the columns you want to print.
  • User feedback: Added a check for empty results to inform you when no matches exist.

If your Column 2 stores numeric values instead of strings, convert the input to the appropriate type before comparing:

codeNum = int(input("What's the code: ").strip())
# Then use file['Column 2'] == codeNum as before

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 22:22:38