Python CSV Writer无法添加Whip列,计算结果未输出问题求助
Fixing Your WHIP Calculation CSV Script
Let's walk through the issues in your code step by step to get that WHIP calculation showing up in your output file:
Key Issues in the Original Code
- Incorrect file opening mode: In Python 3,
csv.DictReaderdoesn't require binary mode (rb). Using'r'(text mode) withnewline=''ensures proper CSV handling and avoids extra blank lines in the output. - Missing 'Whip' in output fields: Your
fieldnameslist didn't include the new 'Whip' column, so the writer wouldn't output it even if you calculated it. - Dictionary manipulation error:
lineis a dictionary (fromDictReader), not a list—you can't useappend()on it. Instead, assign the WHIP value to a new key in the dictionary. - String-to-number conversion: All values read from CSV are strings. You need to convert
BB,H, andIPoutsto integers before doing math, otherwise you'll get errors or nonsensical results. - Case-sensitive header typo: You wrote
line['Ipouts']but the CSV header isIPouts(uppercase I and P)—this would throw a KeyError and crash the script.
Corrected Code
import csv print('Enter start year: ') startYear = input() print('Enter end year: ') endYear = input() # Use text mode with newline='' for proper CSV handling in Python 3 with open('Pitching.csv', 'r', newline='') as csv_file: csv_reader = csv.DictReader(csv_file) # Automatically include all original headers plus the new 'Whip' column fieldnames = csv_reader.fieldnames + ['Whip'] with open('new_stats.csv', 'w', newline='') as new_file: csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames) csv_writer.writeheader() for line in csv_reader: currentYear = line['yearID'] # Convert years to integers for valid comparison if int(currentYear) >= int(startYear) and int(currentYear) <= int(endYear): # Convert CSV string values to integers for calculation walks = int(line['BB']) hits = int(line['H']) inningsPitched = int(line['IPouts']) # Fixed case mismatch here # Calculate WHIP: (Walks + Hits) / Innings Pitched (IPouts divided by 3) innings = inningsPitched / 3.0 # Avoid division by zero if no innings were pitched if innings > 0: whip = (walks + hits) / innings else: whip = 0.0 # Adjust this handling if needed (e.g., leave blank) # Add WHIP to the dictionary as a new key-value pair line['Whip'] = round(whip, 3) # Round to 3 decimals for standard stat formatting csv_writer.writerow(line)
Additional Notes
- I added a check for division by zero (if
inningsPitchedis 0) to prevent runtime errors—feel free to adjust this handling if you want a different placeholder or behavior. - Rounding the WHIP value to 3 decimal places matches standard baseball stat formatting, but you can remove the
round()call if you want full precision. - Using
csv_reader.fieldnames + ['Whip']instead of hardcoding all headers makes the script more maintainable if the original CSV ever gets updated with new columns.
内容的提问来源于stack exchange,提问作者B.Strainer
相关产品推荐
相关产品推荐

