如何在Python中保存数据框表? [英] How can I save table of dataframe in Python?
问题描述
我有一个关于将数据帧放入表并将其另存为png文件的问题.
I have an issue about putting dataframe into to table and saving it as a png file.
为此,我编写了一些如下所示的代码块.
To do that, I wrote some code blocks shown below.
df = pd.DataFrame({'count' : fdf.groupby(['year','Name']).size()}).reset_index()
df = df.sort_values(['year','count'], ascending=[True,False]).set_index(['year','Name'])
df = df.style.background_gradient(cmap='YlOrRd')
df
这是我的df
count
year Name
1950 a 3
b 3
1951 c 3
d 2
e 1
... ... ...
然后,我尝试使用下面显示的代码片段来保存结果,但是没有用.
Then I tried to use this code snippet shown below to save result but it didn't work.
plt.figure(figsize=[15, 15])
ax = plt.subplot()
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
table(ax,f1_df_win_season.data)
plt.savefig('images/image1.png')
尽管我可以在JupyterNotebook中的表中看到所有变量,但在png文件中看不到它.
Although I can see all variables in table in JupyterNotebook, I couldn't see it in png file.
我该如何解决?
这是我的截图
推荐答案
我建议使用matplotlib'table'函数创建表,然后再将其作为背景渐变进行所需的格式化.
I would recommend to create a table using the matplotlib 'table' function and do the desired formatting as background gradients afterwards.
使用创建数据框后
df = pd.DataFrame({'count' : fdf.groupby(['year','Name']).size()}).reset_index()
df = df.sort_values(['year','count'], ascending=[True,False]).set_index(['year','Name'])
您可以像创建/保存表格一样
you can create (and save) your table like
plt.figure(figsize=[15, 15])
ax = plt.subplot()
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
ax.table(cellText=df.reset_index().values,
colLabels=df.reset_index().columns,
loc='center',
cellLoc='center')
plt.savefig('image1.png')
您可以在表格函数中添加所有格式(请参见 https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.table.html )
You can add all the formatting in the table function (see https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.table.html)
这篇关于如何在Python中保存数据框表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!