Pandas 对多个数值进行分组并绘制结果
在这篇文章中,我们将学习如何对多个数值进行分组,并将结果一次性绘制出来。在这里,我们从seaborn库中获取 “exercise.csv “文件,然后形成不同的分组数据并将结果可视化。
对于这个程序,需要的步骤如下。
- 用于数据及其可视化的导入库。
- 创建和导入多列的数据。
- 通过对多个值进行分组,形成一个grouby对象。
- 将分组的数据可视化。
下面是带有一些例子的实现。
例子1 :
在这个例子中,我们从seaborn库中获取数据集 “exercise.csv “文件,然后在 “时间 “一栏的基础上将 “脉搏 “和 “饮食 “两栏分组,形成groupby数据,最后将结果可视化。
# importing packages
import seaborn
# load dataset and view
data = seaborn.load_dataset('exercise')
print(data)
# multiple groupby (pulse and diet both)
df = data.groupby(['pulse', 'diet']).count()['time']
print(df)
# plot the result
df.plot()
plt.xticks(rotation=45)
plt.show()
输出 :
Unnamed: 0 id diet pulse time kind
0 0 1 low fat 85 1 min rest
1 1 1 low fat 85 15 min rest
2 2 1 low fat 88 30 min rest
3 3 2 low fat 90 1 min rest
4 4 2 low fat 92 15 min rest
.. ... .. ... ... ... ...
85 85 29 no fat 135 15 min running
86 86 29 no fat 130 30 min running
87 87 30 no fat 99 1 min running
88 88 30 no fat 111 15 min running
89 89 30 no fat 150 30 min running
[90 rows x 6 columns]
pulse diet
80 no fat NaN
low fat 1.0
82 no fat NaN
low fat 1.0
83 no fat 2.0
...
140 low fat NaN
143 no fat 1.0
low fat NaN
150 no fat 1.0
low fat NaN
Name: time, Length: 78, dtype: float64
例子2:这个例子是对上述例子的修改,以达到更好的视觉效果。
# importing packages
import seaborn
# load dataset
data = seaborn.load_dataset('exercise')
# multiple groupby (pulse and diet both)
df = data.groupby(['pulse', 'diet']).count()['time']
# plot the result
df.unstack().plot()
plt.xticks(rotation=45)
plt.show()
输出 :
示例 3:
在这个例子中,我们从seaborn库中获取了 “exercise.csv “文件,然后通过将 “pulse”、”diet “和 “time “这三列在 “kind “列的基础上分组,形成groupby数据,最后可视化结果。
# importing packages
import seaborn
# load dataset and view
data = seaborn.load_dataset('exercise')
print(data)
# multiple groupby (pulse, diet and time)
df = data.groupby(['pulse', 'diet', 'time']).count()['kind']
print(df)
# plot the result
df.plot()
plt.xticks(rotation=30)
plt.show()
输出 :
Unnamed: 0 id diet pulse time kind
0 0 1 low fat 85 1 min rest
1 1 1 low fat 85 15 min rest
2 2 1 low fat 88 30 min rest
3 3 2 low fat 90 1 min rest
4 4 2 low fat 92 15 min rest
.. ... .. ... ... ... ...
85 85 29 no fat 135 15 min running
86 86 29 no fat 130 30 min running
87 87 30 no fat 99 1 min running
88 88 30 no fat 111 15 min running
89 89 30 no fat 150 30 min running
[90 rows x 6 columns]
pulse diet time
80 no fat 1 min NaN
15 min NaN
30 min NaN
low fat 1 min 1.0
15 min NaN
...
150 no fat 15 min NaN
30 min 1.0
low fat 1 min NaN
15 min NaN
30 min NaN
Name: kind, Length: 234, dtype: float64
例子4:这个例子是对上述例子的修改,以达到更好的视觉效果。
# importing packages
import seaborn
# load dataset
data = seaborn.load_dataset('exercise')
# multiple groupby (pulse, diet, and time)
df = data.groupby(['pulse', 'diet', 'time']).count()['kind']
# plot the result
df.unsatck().plot()
plt.xticks(rotation=30)
plt.show()
输出 :