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

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.DictReader doesn't require binary mode (rb). Using 'r' (text mode) with newline='' ensures proper CSV handling and avoids extra blank lines in the output.
  • Missing 'Whip' in output fields: Your fieldnames list didn't include the new 'Whip' column, so the writer wouldn't output it even if you calculated it.
  • Dictionary manipulation error: line is a dictionary (from DictReader), not a list—you can't use append() 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, and IPouts to integers before doing math, otherwise you'll get errors or nonsensical results.
  • Case-sensitive header typo: You wrote line['Ipouts'] but the CSV header is IPouts (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 inningsPitched is 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:35:24