Pandas:如何使用Groupby和Plot(有例子)。

1,633 阅读2分钟

你可以使用以下方法对pandas DataFrame进行分组和绘图。

方法1:分组并在一个图中画出多条线

#define index column
df.set_index('day', inplace=True)

#group data by product and display sales as line chart
df.groupby('product')['sales'].plot(legend=True)

方法2:分组并在单个子图中绘制线条

pd.pivot_table(df.reset_index(),
               index='day', columns='product', values='sales'
              ).plot(subplots=True)

下面的例子展示了如何在以下pandas DataFrame中实际使用每种方法。

import pandas as pd

#create DataFrame
df = pd.DataFrame({'day': [1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
                   'product': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'],
                   'sales': [4, 7, 8, 12, 15, 8, 11, 14, 19, 20]})

#view DataFrame
df

	day	product	sales
0	1	A	4
1	2	A	7
2	3	A	8
3	4	A	12
4	5	A	15
5	1	B	8
6	2	B	11
7	3	B	14
8	4	B	19
9	5	B	20

方法1:分组并在一个图中绘制多条线

下面的代码显示了如何通过 "产品 "变量对DataFrame进行分组,并在一个图表中绘制每个产品的 "销售额"。

#define index column
df.set_index('day', inplace=True)

#group data by product and display sales as line chart
df.groupby('product')['sales'].plot(legend=True)

pandas groupby and plot

X轴显示的是日期,Y轴显示的是销售额,而每条线显示的是各个产品的销售额。

方法2:按分组并在单个子图中绘制线条

下面的代码显示了如何通过 "产品 "变量对DataFrame进行分组,并在各个子图中绘制每个产品的 "销售额"。

pd.pivot_table(df.reset_index(),
               index='day', columns='product', values='sales'
              ).plot(subplots=True)

pandas groupby and plot in subplots

第一个图显示产品A的销售情况,第二个图显示产品B的销售情况。

注意,我们也可以使用布局参数来指定子图的布局。

例如,我们可以指定子图为一行两列的网格。

pd.pivot_table(df.reset_index(),
               index='day', columns='product', values='sales'
              ).plot(subplots=True, layout=(1,2))

其他资源

下面的教程解释了如何在pandas中创建其他常见的可视化数据。

如何从Pandas DataFrame创建Boxplot
如何从Pandas DataFrame创建Pie Chart
如何从Pandas DataFrame创建Histogram

The postPandas: How to Use Groupby and Plot (With Examples)appeared first onStatology.