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

Python 3绘制年份-犯罪数量柱状图时遇文件读取错误

解决numpy.loadtxt读取CSV时的URLError问题

首先看你的错误提示:urllib.error.URLError: <urlopen error URL not found: C://Users/Andrew/Downloads/Crimes_-_2001_to_present.csv>,这个问题主要是numpy的loadtxt把Windows路径当成URL解析了,再加上可能的路径拼写/文件名匹配问题,导致找不到文件。下面一步步给你解决:

1. 先解决路径和文件名核心问题

关键注意点:

  • 你代码里两次写的文件名不一致:第一次是Crimes_- _2001_to_present.csv(下划线和2001之间有空格),第二次是Crimes_-_2001_to_present.csv(无空格),这大概率是文件找不到的核心原因!一定要确保代码里的文件名和实际文件完全一致。
  • Windows路径推荐用原始字符串(前面加r),避免Python解析转义字符,也能防止numpy误判成URL。比如:
    file_path = r"C:\Users\Andrew\Downloads\Crimes_-_2001_to_present.csv"
    
  • 也可以用双反斜杠\\或者正斜杠/,但原始字符串最稳妥。

2. 修正后的numpy版本代码

我给你调整了代码,增加了文件存在检查,修复了小问题,兼容性更好:

import matplotlib.pyplot as plt
import numpy as np
import os

# 用原始字符串定义路径,确保文件名和实际一致
file_path = r"C:\Users\Andrew\Downloads\Crimes_-_2001_to_present.csv"

# 提前检查文件是否存在,避免报错
if not os.path.exists(file_path):
    print(f"Error: 文件不存在,请检查路径:{file_path}")
else:
    # 读取数值数据
    data = np.loadtxt(file_path, delimiter=',', skiprows=1, usecols=range(1,5))
    data = data.transpose()
    # 读取年份字符串
    xt = np.loadtxt(file_path, dtype='str', delimiter=',', skiprows=1, usecols=(0,))
    
    width = 0.5
    # 用年份的数量代替固定的18,更灵活
    ind = np.arange(len(xt)) + 0.75
    fig, ax = plt.subplots(1,1)
    p0 = ax.bar(ind, data[0], width, color='cyan')
    
    ax.set_ylabel('Number of Crimes')
    ax.set_xlabel('Years')
    ax.set_xticks(ind + width/2.)
    ax.set_xticklabels(xt, rotation=70)
    # 修正拼写错误:Comitted -> Committed
    fig.legend((p0[0]), ('Crime Committed that year'))
    fig.tight_layout()
    # 用plt.show()代替fig.show(),兼容性更好
    plt.show()

3. 更推荐的pandas版本

处理CSV文件,pandas比numpy更简单,不需要分开读取数值和字符串列,代码更简洁,也不容易出路径问题:

import matplotlib.pyplot as plt
import pandas as pd
import os

file_path = r"C:\Users\Andrew\Downloads\Crimes_-_2001_to_present.csv"

if not os.path.exists(file_path):
    print(f"Error: 文件不存在,请检查路径:{file_path}")
else:
    # 一键读取CSV,自动处理列类型
    df = pd.read_csv(file_path)
    
    # 取第一列作为年份,第二列作为犯罪数量(根据你的需求调整列索引)
    years = df.iloc[:, 0]
    crime_counts = df.iloc[:, 1]
    
    fig, ax = plt.subplots(1,1)
    ax.bar(years, crime_counts, width=0.5, color='cyan')
    
    ax.set_ylabel('Number of Crimes')
    ax.set_xlabel('Years')
    # 旋转X轴标签
    ax.tick_params(axis='x', rotation=70)
    ax.legend(['Crime Committed that year'])
    fig.tight_layout()
    plt.show()

额外提示

  • 确认文件路径时,可以直接在文件资源管理器中复制路径:右键文件→属性→安全→对象名称,复制后粘贴到代码里,再加上r变成原始字符串。
  • 如果CSV文件里有缺失值,numpy的loadtxt会报错,pandas的read_csv可以自动处理,这也是用pandas的优势之一。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:06:23