如何用Statsmodels库从Pandas数据帧创建马赛克图?

2024-05-20 01:32:38 发布

您现在位置:Python中文网/ 问答频道 /正文

使用Python3.4、Pandas0.15和Statsmodels 0.6.0,我尝试从数据帧创建一个mosaic plot,如Statsmodels documentation中所述。但是,我只是不明白如何格式化提供给mosaic()函数的输入。

给定一个简单的数据帧:

In:
myDataframe = pd.DataFrame({'size' : ['small', 'large', 'large', 'small', 'large', 'small'], 'length' : ['long', 'short', 'short', 'long', 'long', 'short']})

Out:
  length   size
0   long  small
1  short  large
2  short  large
3   long  small
4   long  large
5  short  small

当试图创建此数据的马赛克图时:

from statsmodels.graphics.mosaicplot import mosaic
mosaic(data=myDataframe, title='Mosaic Plot')

给出ValueError: cannot label index with a null key

由于马赛克图是列联表的可视化,所以我首先尝试用

In:
myCrosstable = pd.crosstab(myDataframe['size'], myDataframe['length'])

Out:
length  long  short
size               
large      1      2
small      2      1

不过,使用myCrosstable作为数据参数也会产生同样的错误。

如何格式化数据帧才能被mosaic()函数接受?文档解释了数据参数: 参数:

data : dict, pandas.Series, np.ndarray, pandas.DataFrame

The contingency table that contains the data. Each category should contain a non-negative number with a tuple as index.

这不是pd.crosstab函数返回的结果吗?如果没有,如何相应地转换数据帧?


Tags: 数据函数indata参数sizelengthlong
2条回答

我用了你的数据和这个代码:

mosaic(myDataframe, ['size', 'length'])

得到这样的图表:

mosaic chart

也可以使用交叉表上的stack函数来避免重新计算列联表。

使用您的代码,mosaic(myCrossTable.stack())可以工作。

相关问题 更多 >