使用熊猫进行多索引和绘图

时间:2019-03-04 21:11:46

标签: pandas plot multi-index

我想将此熊猫DataFrame绘制为三条2D线:no_transfer,transfer和random_transfer,其中每条线分别从0到9列。该DataFrame具有MultiIndex。我还想摆脱“ is_greedy”级别,因为所有值都相同。

                              0    1     2     3  ...      6     7     8     9
config          is_greedy                         ...                         
no_transfer     True        9.0  9.0  14.0  15.0  ...   16.5  15.0  11.0   9.5
transfer        True        9.0  9.5  27.5  10.5  ...   19.5  55.5  14.0  24.0
random_transfer True       35.5  9.0  13.5  10.0  ...   10.0  13.0  27.5  32.0

1 个答案:

答案 0 :(得分:2)

删除索引级别,转置并绘制。

df.reset_index('is_greedy', drop=True).T.plot()

样本数据

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(30, 50, (3, 11)), 
                  index=['no_transfer', 'transfer', 'random_transfer'])
df = df.set_index(10, append=True)
df.index.names=['config', 'is_greedy']
#                            0   1   2   3   4   5   6   7   8   9
#config          is_greedy                                        
#no_transfer     40         35  49  47  36  48  47  39  48  38  32
#transfer        33         35  33  45  38  38  45  36  30  46  36
#random_transfer 36         32  41  36  41  37  35  40  42  49  32

df.reset_index('is_greedy', drop=True).T.plot()

enter image description here


或遍历各行:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
for idx, row in df.iterrows():
    ax.plot(df.columns, row, label=idx[0])
plt.legend()
plt.show()