Pandas数据处理可视化

简介: Pandas数据处理可视化

以下可视化的数据来源为“transcript.xlsx”成绩单文件,他有六列,分别是学生姓名班级数学科目得分体育科目得分python语言得分美学科目得分。基于这个数据表,进行数据处理和可视化操作。

一、垂直柱形图

柱形图,又称长条图、柱状统计图亦称条图条状图棒形图,是一种以长方形的长度为变量的统计图表。长条图用来比较两个或以上的价值(不同时间或者不同条件),只有一个变量,通常利用于较小的数据集分析。长条图亦可横向排列,或用多维方式表达。

代码如下:

1. import pandas as pd            #导入pandas库
2. import matplotlib.pyplot as plt
3. import numpy as np
4. plt.rcParams['font.sans-serif']=['SimHei']
5. plt.rcParams['axes.unicode_minus']=False
6. 
7. excel_file = 'transcript.xlsx'        #导入文件
8. data = pd.read_excel(excel_file)      #读入数据
9. 
10. def func(type):
11.     type_class = data.loc[data['class'] == type]
12.     class_math = type_class["math"]
13.     class_physics = type_class["physics"]
14.     class_python = type_class["python"]
15.     class_aesthetics = type_class["aesthetics"]
16.     type_dic = {}
17.     type_dic["math"] = sum(class_math)/len(class_math)
18.     type_dic["physics"] = sum(class_physics)/len(class_physics)
19.     type_dic["python"] = sum(class_python)/len(class_python)
20.     type_dic["aesthetics"] = sum(class_aesthetics)/len(class_aesthetics)
21. return type_dic
22. 
23. dic_A = func("A")
24. dic_B = func("B")
25. dic_C = func("C")
26. dic_D = func("D")
27. y1 = list(dic_A.values())
28. y2 = list(dic_B.values())
29. y3 = list(dic_C.values())
30. y4 = list(dic_D.values())
31. x = np.arange(len(y1))
32. 
33. #设置柱状图的宽度
34. width = 0.1
35. #绘图
36. plt.figure(figsize=(8,4))
37. plt.bar(x=x,height=y1,width=width,label='math')
38. plt.bar(x=x+width,height=y2,width=width,label='physics')
39. plt.bar(x=x+2*width,height=y3,width=width,label='python')
40. plt.bar(x=x+3*width,height=y4,width=width,label='aesthetics')
41. plt.xlabel('平均成绩')
42. plt.ylabel('班级')
43. 
44. #添加图标题和图例
45. a = [0,1,2,3]
46. labels = ['A', 'B', 'C', 'D']
47. plt.xticks(a,labels,rotation = 30)
48. plt.title('各个班级四个科目平均成绩垂直柱形图')
49. plt.legend(bbox_to_anchor=(0.1, 1))
50. plt.show()

效果如下:

二、垂直堆叠柱形图

垂直堆叠柱状图是柱状图的一种,可以在较小的可视化应用空间内,智能地展示多维的数据差异。支持自定义y轴区间、多系列数据配置以及堆叠式的数据展示

代码如下:

1. import pandas as pd            #导入pandas库
2. import matplotlib.pyplot as plt
3. import numpy as np
4. plt.rcParams['font.sans-serif']=['SimHei']
5. plt.rcParams['axes.unicode_minus']=False
6. 
7. excel_file = 'transcript.xlsx'        #导入文件
8. data = pd.read_excel(excel_file)      #读入数据
9. 
10. def func(type):
11.     type_class = data.loc[data['class'] == type]
12.     class_math = type_class["math"]
13.     class_physics = type_class["physics"]
14.     class_python = type_class["python"]
15.     class_aesthetics = type_class["aesthetics"]
16.     type_dic = {}
17.     type_dic["math"] = sum(class_math)/len(class_math)
18.     type_dic["physics"] = sum(class_physics)/len(class_physics)
19.     type_dic["python"] = sum(class_python)/len(class_python)
20.     type_dic["aesthetics"] = sum(class_aesthetics)/len(class_aesthetics)
21. return type_dic
22. 
23. dic_A = func("A")
24. dic_B = func("B")
25. dic_C = func("C")
26. dic_D = func("D")
27. y1 = list(dic_A.values())
28. y2 = list(dic_B.values())
29. y3 = list(dic_C.values())
30. y4 = list(dic_D.values())
31. y_list = [y1,y2,y3,y4]
32. x = np.arange(len(y1))
33. width = 0.1
34. plt.xlabel('班级')
35. plt.ylabel('分数')
36. def push(i):
37. #设置柱状图的宽度
38. if i == 0:
39.         plt.bar(x[i], y_list[i][0], alpha=0.7, width=0.3, color='green',label = "math")
40.         plt.bar(x[i], y_list[i][1], alpha=0.7, width=0.3, color='red',bottom=y_list[i][0],label = "physics")
41.         plt.bar(x[i], y_list[i][2], alpha=0.7, width=0.3, color='black',bottom=y_list[i][1],label = "python")
42.         plt.bar(x[i], y_list[i][3], alpha=0.7, width=0.3, color='yellow',bottom=y_list[i][2],label = "aesthetics")
43. else:
44.         plt.bar(x[i], y_list[i][0], alpha=0.7, width=0.3, color='green')
45.         plt.bar(x[i], y_list[i][1], alpha=0.7, width=0.3, color='red', bottom=y_list[i][0])
46.         plt.bar(x[i], y_list[i][2], alpha=0.7, width=0.3, color='black', bottom=y_list[i][1])
47.         plt.bar(x[i], y_list[i][3], alpha=0.7, width=0.3, color='yellow', bottom=y_list[i][2])
48. push(0)
49. push(1)
50. push(2)
51. push(3)
52. 
53. a = [0,1,2,3]
54. labels = ['A', 'B', 'C', 'D']
55. plt.xticks(a,labels,rotation = 30)
56. plt.legend(bbox_to_anchor=(0.30, 0.75))
57. plt.title('垂直堆叠柱形图')
58. plt.show()

效果如下:

三、直方图

直方图又称质量分布图,是一种统计报告图,它是根据具体数据的分布情况,画成以组距为底边、以频数为高度的一系列连接起来的直方型矩形图

代码如下:

1. import pandas as pd            #导入pandas库
2. import matplotlib.pyplot as plt
3. import numpy as np
4. plt.rcParams['font.sans-serif']=['SimHei']
5. plt.rcParams['axes.unicode_minus']=False
6. 
7. excel_file = 'transcript.xlsx'        #导入文件
8. data = pd.read_excel(excel_file)      #读入数据
9. math = data["math"]
10. physics = data["physics"]
11. python = data["python"]
12. aesthetics = data["aesthetics"]
13. 
14. # 计算组数
15. def histo(a,subject):
16.     d = 3  # 组距
17.     num_bins = (max(a) - min(a)) // d
18. # 设置图形大小
19.     plt.figure(figsize=(20, 8), dpi=80)
20.     plt.hist(a, num_bins)
21. # 设置x轴刻度
22.     plt.xticks(range(min(a), max(a) + d, d))
23. # 设置网格
24.     plt.grid(alpha=0.4)
25.     plt.ylabel(subject+"分数",fontsize=60)
26.     plt.title(subject+"科目直方图",fontsize=60)
27. # print(math)
28. histo(math,"math")
29. histo(physics,"physics")
30. histo(python,"python")
31. histo(aesthetics,"aesthetics")
32. plt.show()

效果如下:

四、分布箱线图

线是用来表示一组或多组连续型数据分布的中心位置和散布范围的形,因形似箱子故取名为线

代码如下:

按各个科目的分数分布箱线图:

1. import pandas as pd
2. import matplotlib.pyplot as plt
3. 
4. # 读取excel文件
5. file_01 = pd.read_excel("transcript.xlsx")
6. 
7. fig = plt.figure(figsize=(16, 8))
8. d1 = file_01['math']
9. d2 = file_01['physics']
10. d3 = file_01['python']
11. d4 = file_01['aesthetics']
12. 
13. label = 'math', 'physics', 'python', 'aesthetics'
14. plt.boxplot([d1, d2, d3, d4], labels=label)  # label设置横轴每个箱图对应的横坐标
15. plt.xticks(fontproperties='KaiTi')
16. plt.xlabel('变量', fontproperties='KaiTi',fontsize=40)
17. plt.ylabel('变量值', fontproperties='KaiTi',fontsize=40)
18. plt.show()

按班级的科目分数分布箱线图:

1. import pandas as pd
2. import matplotlib.pyplot as plt
3. 
4. # 读取excel文件
5. data = pd.read_excel("transcript.xlsx")
6. def func(type):
7.     type_class = data.loc[data['class'] == type]
8.     d1 = type_class["math"]
9.     d2 = type_class["physics"]
10.     d3 = type_class["python"]
11.     d4 = type_class["aesthetics"]
12.     label = 'math', 'physics', 'python', 'aesthetics'
13.     plt.boxplot([d1, d2, d3, d4], labels=label)  # label设置横轴每个箱图对应的横坐标
14.     plt.xticks(fontproperties='KaiTi')
15.     plt.xlabel('变量', fontproperties='KaiTi', fontsize=20)
16.     plt.ylabel('变量值', fontproperties='KaiTi', fontsize=20)
17.     plt.show()
18. func("A")
19. func("B")
20. func("C")
21. func("D")

效果如下:

五、总结

  1. Pandas对数据进行筛选,比如说绘制各个班级四个科目平均成绩的垂直柱形图时,需要对不同班级进行筛选,则利用pandas中的type_class = data.loc[data['class'] == type],进行筛选,这里的type即是班级种类ABCD。
  2. 函数封装思想,在整个编程中,运用了蕴含了大量自己封装的函数,因为在画图中有很多重复的操作,比如说画不同科目的直方图时,仅是科目类别对应的数据不一样,代码逻辑和框架是一样的。运用函数封装使得代码更加啊清晰,高效,也能够减少代码量。
  3. 用字典存储对应数据。type_dic = {}键是不同的科目名,键是平均成绩。这样在画图时,键可以作为图列,y1 = list(dic_A.values()),取得y值绘图。
  4. plt.rcParams['font.sans-serif']=['SimHei']plt.rcParams['axes.unicode_minus']=False 防止中文标签标题等不能正常显示。
  5. 导入文件,读取数据的相关操作:excel_file = 'transcript.xlsx'#导入文件data = pd.read_excel(excel_file)      #读入数据
  6. 绘制垂直堆叠柱形图时,plt.bar()中注意设置bottom参数是从上一个科目上开始的,这样才能够达到堆叠的效果。
  7. 绘制各个科目的直方图时,设置了一个d组距,将最大值减去最小值除以组距作为num_bins,用plt进行画图,设置网格使效果更加直观。绘制各个科目的分数分布箱线图,label = 'math', 'physics', 'python', 'aesthetics'设置横轴每个箱图对应的横坐标


相关文章
|
29天前
|
数据采集 数据可视化 数据挖掘
Pandas函数大合集:数据处理神器一网打尽!
Pandas函数大合集:数据处理神器一网打尽!
31 0
|
29天前
|
机器学习/深度学习 数据处理 Python
从NumPy到Pandas:轻松转换Python数值库与数据处理利器
从NumPy到Pandas:轻松转换Python数值库与数据处理利器
46 0
|
11天前
|
并行计算 大数据 数据处理
亿级数据处理,Pandas的高效策略
在大数据时代,数据量的爆炸性增长对处理技术提出更高要求。本文介绍如何利用Python的Pandas库及其配套工具高效处理亿级数据集,包括:采用Dask进行并行计算,分块读取以减少内存占用,利用数据库进行复杂查询,使用内存映射优化Pandas性能,以及借助PySpark实现分布式数据处理。通过这些方法,亿级数据处理变得简单高效,助力我们更好地挖掘数据价值。
18 1
|
19天前
|
机器学习/深度学习 并行计算 大数据
【Python篇】深入挖掘 Pandas:机器学习数据处理的高级技巧
【Python篇】深入挖掘 Pandas:机器学习数据处理的高级技巧
45 3
|
29天前
|
数据采集 数据挖掘 数据处理
Pandas实践:南京地铁数据处理分析
Pandas实践:南京地铁数据处理分析
26 2
|
14天前
|
数据采集 数据可视化 数据挖掘
Python 数据分析实战:使用 Pandas 进行数据清洗与可视化
【10月更文挑战第3天】Python 数据分析实战:使用 Pandas 进行数据清洗与可视化
53 0
|
2月前
|
数据可视化 Python
Pandas可视化指南:从零教你绘制数据图表
Pandas可视化指南:从零教你绘制数据图表
|
2月前
|
数据采集 数据挖掘 数据处理
解锁Python数据分析新技能!Pandas实战学习,让你的数据处理能力瞬间飙升!
【8月更文挑战第22天】Python中的Pandas库简化了数据分析工作。本文通过分析一个金融公司的投资数据文件“investment_data.csv”,介绍了Pandas的基础及高级功能。首先读取并检查数据,包括显示前几行、列名、形状和数据类型。随后进行数据清洗,移除缺失值与重复项。接着转换日期格式,并计算投资收益。最后通过分组计算平均投资回报率,展示了Pandas在数据处理与分析中的强大能力。
41 0
|
3月前
|
机器学习/深度学习 数据可视化 搜索推荐
Pandas 和 Matplotlib 可视化
【7月更文挑战第14天】Pandas 和 Matplotlib 是Python数据分析的核心库,用于数据探索性可视化。首先,通过`pip install pandas matplotlib`安装库。接着,使用`pd.read_csv()`加载CSV数据,`df.describe()`查看统计信息。利用Matplotlib的`hist()`, `scatter()`, 和 `boxplot()`绘制直方图、散点图和箱线图,展示数据分布和关系。通过`subplots()`创建多图展示,自定义样式如颜色、标记,并添加注释和标题。高级技巧包括热力图、时间序列图、分组可视化及Seaborn和Plotly
51 10
|
2月前
|
存储 数据可视化 数据挖掘
Python 3 中使用 pandas 和 Jupyter Notebook 进行数据分析和可视化
Python 3 中使用 pandas 和 Jupyter Notebook 进行数据分析和可视化
42 0