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)) <15excludes values with exactly 3 or 15 characters. Since your requirement is 3–15 characters (inclusive), adjust it to>=3and<=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
intstrips 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
locto 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
相关产品推荐
相关产品推荐

