我们可以使用pandas库中的groupby()函数按多列对数据进行分组,然后使用matplotlib库进行数据可视化。以下是一个基本的示例代码:
import pandas as pd
import matplotlib.pyplot as plt
# 假设我们有以下数据集
df = pd.DataFrame({
'Category': ['A', 'A', 'B', 'B', 'C', 'C', 'C'],
'Country': ['USA', 'UK', 'USA', 'USA', 'UK', 'USA', 'UK'],
'Value': [10, 12, 8, 6, 5, 3, 2]
})
# 按 Category 和 Country 分组
grouped = df.groupby(['Category', 'Country'])
# 绘制每个分组中 Value 的直方图
fig, axs = plt.subplots(len(grouped), sharex=True, sharey=True)
for i, (name, group) in enumerate(grouped):
axs[i].hist(group['Value'], bins=10)
axs[i].set(title=name)
plt.show()
运行以上代码,将会得到三张子图,每个子图表示一个分组中 Value 的分布情况。
上一篇:按多列分组,然后按结果进行排序。
下一篇:按多列分组,所有计数为0。