使用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))withastype(str): This is a more efficient and concise way to convert column values to strings in pandas. - Added
format='%d-%m'topd.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ç
相关产品推荐
相关产品推荐

