Boxplot由python pandas中的列分层

use*_*827 7 python matplotlib boxplot pandas

我想为以下pandas数据帧绘制一个boxplot:

> p1.head(10)

   N0_YLDF    MAT
0     1.29  13.67
1     2.32  10.67
2     6.24  11.29
3     5.34  21.29
4     6.35  41.67
5     5.35  91.67
6     9.32  21.52
7     6.32  31.52
8     3.33  13.52
9     4.56  44.52
Run Code Online (Sandbox Code Playgroud)

我想箱形图是'N0_YLDF'列,但它们应该用'MAT'分层.当我使用foll时.命令:

p1.boxplot(column='N0_YLDF',by='MAT')
Run Code Online (Sandbox Code Playgroud)

它使用所有唯一的MAT值,在完整的p1数据帧数约为15,000.这导致难以理解的箱线图.

有没有什么方法可以对MAT值进行分层,这样我就可以获得不同的第二个MAT值的N0_YLDF箱图,依此类推....

谢谢!

Mar*_*ius 8

熊猫拥有cutqcut功能,使分层像这样简单的变量:

# Just asking for split into 4 equal groups (i.e. quartiles) here,
# but you can split on custom quantiles by passing in an array
p1['MAT_quartiles'] = pd.qcut(p1['MAT'], 4, labels=['0-25%', '25-50%', '50-75%', '75-100%'])
p1.boxplot(column='N0_YLDF', by='MAT_quartiles')
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述


CT *_*Zhu 6

pandas.qcut将给你分位数,但类似于直方图的操作将需要一些numpy技巧,这在这里派上用场:

_, breaks = np.histogram(df.MAT, bins=5)
ax = df.boxplot(column='N0_YLDF', by='Class')
ax.xaxis.set_ticklabels(['%s'%val for i, val in enumerate(breaks) if i in df.Class])
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

数据框现在看起来像这样:

   N0_YLDF    MAT  Class
0     1.29  13.67      1
1     2.32  10.67      0
2     6.24  11.29      1
3     5.34  21.29      1
4     6.35  41.67      2
5     5.35  91.67      5
6     9.32  21.52      1
7     6.32  31.52      2
8     3.33  13.52      1
9     4.56  44.52      3

[10 rows x 3 columns]
Run Code Online (Sandbox Code Playgroud)

它也可以用来获得四分位数:

breaks = np.asarray(np.percentile(df.MAT, [25,50,75,100]))
df['Class'] = (df.MAT.values > breaks[..., np.newaxis]).sum(0)
ax = df.boxplot(column='N0_YLDF', by='Class')
ax.xaxis.set_ticklabels(['%s'%val for val in breaks])
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述