我可以使用以下代码在数字上绘制单头数据帧:
plt.table(cellText=df.round(4).values, cellLoc='center', bbox=[0.225, 1, 0.7, 0.15],
rowLabels=[' {} '.format(i) for i in df.index], rowLoc='center',
rowColours=['silver']*len(df.index), colLabels=df.columns, colLoc='center',
colColours=['lightgrey']*len(df.columns), colWidths=[0.1]*len(df.columns))
我的问题是:是否可以使用多索引列绘制数据框?我想要两个单独的"行"对于我的多标题,所以一个标题行中的元组不好。如果有可能,我想在两个标题上应用上述样式(颜色)(为多标题设置不同的颜色会很棒。)
以下是一个示例数据框:
df = pd.DataFrame([[11, 22], [13, 23]],
columns=pd.MultiIndex.from_tuples([('main', 'sub_1'), ('main', 'sub_2')]))
结果:
main
sub_1 sub_2
0 11 22
1 13 23
答案 0 :(得分:2)
好的,我使用“技巧”来解决这个问题:绘制一个只有一个单元格的新表,没有列标题,没有行索引。唯一的单元格值是原始顶部标题。并将此新表放在旧(单标题)表的顶部。 (这不是最好的解决方案,但有效......)。
代码:
df = pd.DataFrame([[11, 22], [13, 23]], columns=['sub_1', 'sub_2'])
# First plot single-header dataframe (headers = ['sub_1', 'sub_2'])
plt.table(cellText=df.round(4).values, cellLoc='center', bbox=[0.225, 1, 0.7, 0.15],
rowLabels=[' {} '.format(i) for i in df.index], rowLoc='center',
rowColours=['silver']*len(df.index), colLabels=df.columns, colLoc='center',
colColours=['lightgrey']*len(df.columns), colWidths=[0.1]*len(df.columns))
# Then plot a new table with one cell (value = 'main')
plt.table(cellText=[['main']], cellLoc='center', bbox=[0.225, 1.15, 0.7, 0.05],
cellColours=[['Lavender']])