Thursday 21 September 2023

How to Pretty Print DataFrames in Pandas?

Using ‘tabulate’ module, we can pretty print the data frame content.

Example

table = tabulate(df, headers='keys', tablefmt='pretty')

 

‘tabulate()’ function takes the DataFrame ‘df’ as the first argument. I specified the headers parameter as 'keys' to use the column names as the table headers and the tablefmt parameter is set to 'pretty' to generate a pretty print table.

 

pretty_print.py

import pandas as pd
from tabulate import tabulate

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Krishna"],
        'Age': [34, 35, 29, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Education': ['Graduate', 'Post Graduate', 'PHD', 'Graduate', 'Graduate', 'Intermediate']}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

table = tabulate(df, headers='keys', tablefmt='pretty')
print('\ntable\n',table)

 

Output

Original DataFrame
       Name  Age       City  Gender      Education
0   Krishna   34  Bangalore    Male       Graduate
1     Sailu   35  Hyderabad  Female  Post Graduate
2      Joel   29  Hyderabad    Male            PHD
3     Chamu   35    Chennai  Female       Graduate
4  Jitendra   52  Bangalore    Male       Graduate
5   Krishna   34    Chennai    Male   Intermediate

table
 +---+----------+-----+-----------+--------+---------------+
|   |   Name   | Age |   City    | Gender |   Education   |
+---+----------+-----+-----------+--------+---------------+
| 0 | Krishna  | 34  | Bangalore |  Male  |   Graduate    |
| 1 |  Sailu   | 35  | Hyderabad | Female | Post Graduate |
| 2 |   Joel   | 29  | Hyderabad |  Male  |      PHD      |
| 3 |  Chamu   | 35  |  Chennai  | Female |   Graduate    |
| 4 | Jitendra | 52  | Bangalore |  Male  |   Graduate    |
| 5 | Krishna  | 34  |  Chennai  |  Male  | Intermediate  |
+---+----------+-----+-----------+--------+---------------+

 


Previous                                                 Next                                                 Home

No comments:

Post a Comment