以下是一个使用Python中的pandas和matplotlib库来生成报表的示例代码,该报表按特定年龄组对数据进行分组并生成柱状图。
import pandas as pd
import matplotlib.pyplot as plt
# 创建示例数据
data = {
'姓名': ['张三', '李四', '王五', '赵六', '钱七'],
'年龄': [28, 33, 45, 29, 35],
'收入': [5000, 6000, 7000, 5500, 8000]
}
df = pd.DataFrame(data)
# 将年龄分组
age_groups = pd.cut(df['年龄'], bins=[0, 30, 40, 50], labels=['30岁以下', '30-40岁', '40岁以上'])
# 按年龄组计算平均收入
avg_income_by_age = df.groupby(age_groups)['收入'].mean()
# 生成柱状图
avg_income_by_age.plot(kind='bar')
# 添加标题和标签
plt.title('按年龄组的平均收入')
plt.xlabel('年龄组')
plt.ylabel('平均收入')
# 显示图表
plt.show()
运行以上代码会生成一个柱状图,横轴表示年龄组,纵轴表示平均收入。