3 回答

TA贡献1802条经验 获得超6个赞
Pandas允许您使用matplotlib绘制表(此处有详细信息)。通常,这会将表格直接绘制到您不想要的图表(带有轴和所有内容)上。但是,可以先删除这些:
import matplotlib.pyplot as plt
import pandas as pd
from pandas.table.plotting import table # EDIT: see deprecation warnings below
ax = plt.subplot(111, frame_on=False) # no visible frame
ax.xaxis.set_visible(False) # hide the x axis
ax.yaxis.set_visible(False) # hide the y axis
table(ax, df) # where df is your data frame
plt.savefig('mytable.png')
输出可能不是最漂亮的,但是您可以在此处找到table()函数的其他参数。也感谢这篇文章提供了有关如何在matplotlib中删除轴的信息。
编辑:
这是一种使用上述方法进行绘图时模拟多索引的方式(无疑是很hacky)。如果您有一个称为df的多索引数据框,如下所示:
first second
bar one 1.991802
two 0.403415
baz one -1.024986
two -0.522366
foo one 0.350297
two -0.444106
qux one -0.472536
two 0.999393
dtype: float64
首先重置索引,使它们成为普通列
df = df.reset_index()
df
first second 0
0 bar one 1.991802
1 bar two 0.403415
2 baz one -1.024986
3 baz two -0.522366
4 foo one 0.350297
5 foo two -0.444106
6 qux one -0.472536
7 qux two 0.999393
通过将它们设置为空字符串,从高阶多索引列中删除所有重复项(在我的示例中,我在“ first”中仅具有重复索引):
df.ix[df.duplicated('first') , 'first'] = ''
df
first second 0
0 bar one 1.991802
1 two 0.403415
2 baz one -1.024986
3 two -0.522366
4 foo one 0.350297
5 two -0.444106
6 qux one -0.472536
7 two 0.999393
将“索引”上的列名称更改为空字符串
new_cols = df.columns.values
new_cols[:2] = '','' # since my index columns are the two left-most on the table
df.columns = new_cols
现在调用表格函数,但将表格中的所有行标签设置为空字符串(这可确保不显示绘图的实际索引):
table(ax, df, rowLabels=['']*df.shape[0], loc='center')
等:
您不太漂亮但功能齐全的多索引表。
编辑:弃用警告
正如评论中指出的,import语句用于table:
from pandas.tools.plotting import table
现在已在较新版本的熊猫中弃用,而支持:
from pandas.plotting import table
添加回答
举报