如何绘制按熊猫列名称分组的箱形图?

时间:2020-05-24 16:59:52

标签: python pandas dataframe boxplot

我的数据框:

     Q   JJ    R    S   R'  S'    P    T   JJ    Q  ...    P    T   JJ    Q  \
0 -0.2  0.0  6.1 -1.0  0.0   0  0.6  2.1  0.0  0.0  ...  0.9  3.9 -0.3  0.0   
1 -0.6  0.0  7.2  0.0  0.0   0  0.4  1.5  0.0  0.0  ...  0.4  2.6 -0.5  0.0   
2  1.0  0.0  4.5 -2.8  0.0   0  0.3  2.5  0.8 -0.4  ...  0.4  3.4  0.9  0.0   
3  0.9  0.0  7.8 -0.7  0.0   0  1.1  1.9  0.1  0.0  ...  0.6  3.0  0.1  0.0   
4  0.0  0.0  5.2 -1.4  0.0   0  0.9  2.3  0.1  0.0  ... -0.2  2.9 -0.4  0.0   

      R    S   R'  S'    P    T  
0   9.0 -0.9  0.0   0  0.9  2.9  
1   8.5  0.0  0.0   0  0.2  2.1  
2   9.5 -2.4  0.0   0  0.3  3.4  
3  12.2 -2.2  0.0   0  0.4  2.6  
4  13.1 -3.6  0.0   0 -0.1  3.9 

我正在尝试绘制按列名分组的箱形图(有8个组,因此我希望有8个箱形图)。 我用过:

bp = df_net_wave_amplitude_for_std.plot.box(figsize=(20,8))

bp = df_net_wave_amplitude_for_std.boxplot(figsize=(20,8))

enter image description here 但我得到的是x轴上的所有列,而不是按名称分组:

1 个答案:

答案 0 :(得分:0)

我知道了: 首先,我应该对数据进行处理:

df_net_wave_amplitude_for_std = df_net_wave_amplitude_for_std.stack()

然后我安排了结果:重置索引,摆脱了多余的列(称为“ level_0”)并重命名了列:

df_net_wave_amplitude_for_std = df_net_wave_amplitude_for_std.reset_index()
del df_net_wave_amplitude_for_std['level_0']
df_net_wave_amplitude_for_std.columns = ['Wave', 'data']

最后我可以使用boxplot函数:

bp = df_net_wave_amplitude_for_std.boxplot('data', by='Wave', figsize=(20,8))