我正在使用Python 3.4、Pandas 0.15和Statsmodels 0.6.0尝试根据Statsmodels文档中描述的方式,从数据框创建一个马赛克图。然而,我不理解提供给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
函数返回的内容吗?如果不是,我该如何相应地转换数据框呢?
mosaic
的第二个参数是你想要用来调整方块大小的列列表。如果这不能解决问题,也许可以尝试提出一个单独的问题。 - Primer