Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

pandas - How can I save table of dataframe in Python?

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

Here is my 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')

Although I can see all variables in table in JupyterNotebook, I couldn't see it in png file.

How can I fix it?

Here is my screenshot

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would recommend to create a table using the matplotlib 'table' function and do the desired formatting as background gradients afterwards.

After creating the dataframe with

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')

You can add all the formatting in the table function (see https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.table.html)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...