熊猫-具有多个索引的线形图子图



我想在每个客户的单独文件中为每个客户创建每个代码的线形图子图。

          Date    Code  Customer     Purchases
1    6/22/2016   6-BZt     Piggy             8
2    6/22/2016   7rTPn     Piggy             1
3    6/22/2016   Hb4vZ     Piggy             1
4    6/22/2016   L0xs5     Piggy            94
5    6/22/2016   S5cLN     Goose             2
6    6/22/2016   k4Yp5     Goose             1
8    6/21/2016   6-BZt     Goose             8
9    6/21/2016   7rTPn     Piggy             1
10   6/21/2016   Hb4vZ     Piggy             1
11   6/21/2016   L0xs5     Piggy            94
12   6/21/2016   S5cLN     Goose             2
13   6/21/2016   k4Yp5     Goose             1

我试着

lineSess = lineSess.set_index(['Date', 'Customer', 'Code'])
lineSess.unstack().plot(subplots=True)

但是它没有按我想要的方式输出

因此,我认为您需要执行的操作顺序是首先将数据框拆分为每个Customer的单独数据框,设置索引,然后解开堆栈并绘图。给定任意数量的客户,你可以这样做

lineSess.sort_values(by='Customer', inplace=True)
lineSess.set_index('Customer', inplace=True)
# get list of unique customer names
customers = lineSess.index.unique().tolist()
# create an empty dataframe for each customer name
customer_dfs = {k: v for k, v in zip(customers, [pd.DataFrame()]*len(customers))}
# fill the empty dataframes with the data corresponding to each particular customer
for key, df in customer_dfs.iteritems(): # customer_dfs.items() for python-3.x
    df = lineSess.loc[lineSess.index==key]
    df = df.set_index(['Date', 'Code'], drop=True)
    df['Purchases'].unstack(level='Code').plot(subplots=True, title=key)

使用您提供的数据,这些图看起来会很枯燥,因为每天的购买数量并没有变化。但假设这只是数据集的一部分,那么这些图可能会提供更多信息。

最新更新