Python处理CSV文件:采购订单数据统计需求求助
Fixing Your Python CSV Purchase Stats Code
Hey there! Let's get your code sorted to handle all four of your tasks. I spotted a couple of small issues in your current code (like a misnamed variable home_runs that doesn’t relate to your data, and you might be grabbing the wrong column for purchase amounts), so let’s rebuild it properly.
First, let’s assume your purchases.csv has a header row (like Order ID,Amount) and each subsequent row has the order details, with the purchase amount in the second column (index 1). If your CSV doesn’t have a header, we can adjust that too—just remove one line we’ll mention later.
Here’s the complete working code:
import csv # Initialize all tracking variables to 0 total_entries = 0 total_amount = 0 high_value_count = 0 high_value_total = 0 with open('purchases.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') # Skip the header row (delete this line if your CSV has no header) next(readCSV) for row in readCSV: # Convert amount from string to float, clean up extra spaces try: amount = float(row[1].strip()) except ValueError: # Skip rows with invalid amount values to avoid crashes continue # Update overall purchase stats total_entries += 1 total_amount += amount # Track high-value purchases (over $1800) if amount > 1800: high_value_count += 1 high_value_total += amount # Calculate averages (handle edge cases where there's no data) average_purchase = round(total_amount / total_entries, 3) if total_entries > 0 else 0.0 high_value_average = round(high_value_total / high_value_count, 3) if high_value_count > 0 else 0.0 # Print results in your required format print(f"Total Number of Purchases: {total_entries}") print(f"Amount of Average Purchase: {average_purchase}") print(f"Number of Purchase Orders over $1,800: {high_value_count}") print(f"Amount of Average Purchases over $1,800: {high_value_average}")
Let’s break down what this code does:
- Variable Setup: We start with all counters and totals set to 0 so we can increment them as we process each row.
- Header Handling: The
next(readCSV)line skips the first header row so it doesn’t get counted as a purchase entry. Remove this line if your CSV has no header. - Data Cleaning & Conversion: We convert the amount column from a string to a float (since CSVs read all data as strings) and use
strip()to remove extra spaces. Thetry/exceptblock skips any rows with invalid amount values to prevent errors. - Stat Tracking: For each valid row, we update the total entry count and total purchase amount. We also check if the amount is over 1800 and update the high-value counters accordingly.
- Average Calculation: We use
round()to get three decimal places, and add checks to avoid division by zero (in case there are no purchases or no high-value purchases). - Formatted Output: We print each stat exactly as your required format specifies.
Notes on your original code:
- You had
home_runsin your loop—this was probably a copy-paste error, and should have referenced your purchase data list. - You were adding
row[0]to your list, which is likely the order ID, not the purchase amount. We switched torow[1]for the amount (adjust this index if your amount is in a different column). - Your original code only tried to count total entries; we’ve expanded it to track all four required metrics.
内容的提问来源于stack exchange,提问作者coderchick2016
相关产品推荐
相关产品推荐

