Hoy可以在pandas中按照boxplot绘制一组来删除未使用的类别吗?

时间:2016-09-07 23:21:49

标签: python-3.x pandas matplotlib boxplot

长话短说。如何从pandas中的类别列绘制分组的boxplot,并仅显示子集中的当前类别而不是所有可能的类别。 enter image description here

[可重现的例子]

我有一个带有factor列的pandas数据帧,我想绘制一个boxplot。如果我按因子绘图就可以了。如果我执行子集并按因子绘制箱线图,也可以,并且仅绘制子集中存在的因子。但是,如果我将列设置为类别,那么即使它们不存在,所有类别也会在框图中绘制。

- 创建数据框

import pandas as pd
import numpy as np
x = ['A']*150 + ['B']*150 + ['C']*150 + ['D']*150 + ['E']*150 + ['F']*150
y = np.random.randn(900)
z = ['X']*450 + ['Y']*450
df = pd.DataFrame({'Letter':x, 'N':y, 'type':z})
print(df.head())
print(df.tail())

- 按因子绘制

df.boxplot(by='Letter')

enter image description here

- 绘制子集(仅绘制子集中的类别,但按字母顺序排序,而不是按照所需顺序排序)

df[df['type']=='X'].boxplot(by='Letter')

enter image description here

- 将因子转换为类别并绘制子集以使集合有序:即使子集中缺少这些类别,也会绘制所有类别。好的部分是他们在“wanted_sort_order”

df['Letter2'] = df['Letter'].copy()
df['Letter2'] = df['Letter2'].astype('category')
# set a category in order to sort the factor in specific order
df['Letter2'].cat.set_categories(df['Letter2'].drop_duplicates().tolist()[::-1], inplace=True)
df[df['type']=='X'].boxplot(by='Letter2')

enter image description here

1 个答案:

答案 0 :(得分:1)

创建DataFrame(第一个代码块)后,请尝试以下操作:

df['Letter2'] = pd.Categorical(df['Letter'], list('BAC'))
df[df['type']=='X'].boxplot(by='Letter2')

结果:

enter image description here

pd.Categorical正在做的只是将NaN设置为您的类别列表中的任何内容(第二个参数),.boxplot()自然只是忽略它并仅绘制您的类别正在寻找。