from sqlalchemy import create_engine
# 创建数据库引擎
engine = create_engine('mysql+pymysql://username:password@localhost/dbname')
# 查询所有学生的论文发表记录
query = "SELECT * FROM student_publications"
result = pd.read_sql(query, engine)
print(result.head())
]]>
我们可以将查询到的结果保存到一个Pandas DataFrame中,这样后续的分析就方便多了。
接下来呢?我们要怎么处理这些数据?
假设我们想统计每位学生发表的文章数量,可以用Pandas提供的`groupby`函数。
# 统计每位学生发表的文章数量
publication_counts = result.groupby('student_id')['publication_title'].count()
print(publication_counts)
]]>
这样就能知道每个学生的贡献了!如果我们还想根据年份查看趋势怎么办?
可以继续扩展,比如按年份分组并绘制折线图。
import matplotlib.pyplot as plt
# 按年份统计发表数量
yearly_counts = result.groupby(result['publication_date'].dt.year)['publication_title'].count()
# 绘制折线图
yearly_counts.plot(kind='line')
plt.title('Annual Publication Trends')
plt.xlabel('Year')
plt.ylabel('Number of Publications')
plt.show()
]]>
太棒了!有了这些工具,我们不仅能快速获取信息,还能直观地看到变化趋势。