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

使用Jupyter Notebook出现语法错误,求原因分析(附相关代码)

排查Jupyter Notebook中的语法错误

Hey there! Let's break down the syntax error in your code and fix it step by step.

核心错误原因

The immediate syntax error comes from the last line of your code:

print accidents.mean()

This is Python 2 syntax, but Jupyter Notebook almost always runs on Python 3 by default. In Python 3, print is a built-in function, so you must wrap its argument in parentheses. Missing these parentheses will throw a SyntaxError.

修正后的完整代码

Here's your revised code with the syntax fix plus some minor improvements for readability and robustness:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Load the accident data
data = pd.read_csv("files/ch04/ACCIDENTS_GU_BCN_2013.csv", encoding='unicode_escape')

# Create combined date string and convert to datetime
data['Date'] = data[u'Dia de mes'].astype(str) + '-' + data[u'Mes de any'].astype(str)
# Specify the date format to avoid parsing ambiguities
data['Date'] = pd.to_datetime(data['Date'], format='%d-%m')

# Group by date and count accidents per day
accidents = data.groupby(['Date']).size()

# Fixed print statement (Python 3 compatible)
print(accidents.mean())

额外优化说明

  • Replaced apply(lambda x: str(x)) with astype(str): This is a more efficient and concise way to convert column values to strings in pandas.
  • Added format='%d-%m' to pd.to_datetime: Explicitly defining the date format ensures pandas parses your day-month strings correctly, even if your system's default date format differs.

内容的提问来源于stack exchange,提问作者Çağlar Seviç

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 09:57:34