How to save Pandas DataFrame as PDF

You can save the Pandas DataFrame as PDF File with the given code.

# Import the required Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

# Initialize a dictionary
dict = {'Students':['Harry', 'John', 'Hussain', 'Satish'],
        'Scores':[77, 59, 88, 93]}

# Create a DataFrame
df = pd.DataFrame(dict)

# Set the figure size & hide the axes
fig, ax =plt.subplots(figsize=(5,1))
ax.axis('tight')
ax.axis('off')
ax.table(cellText=df.values, colLabels=df.columns, loc='center')

# Save the DataFrame as PDF
a = PdfPages("Data.pdf")
a.savefig(fig, bbox_inches='tight')
a.close()

Free Learning Resources

Recommended Laptops

Leave a Comment

Your email address will not be published.