Python – Center align column headers of a Pandas DataFrame



To center align column headers, use the display.colheader_justify and ‘center’ value. Import the require library −

import pandas as pd

Create a DataFrame with 2 columns −

dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'], "Reg_Price": [7000.5057, 1500, 5000.9578, 8000, 9000.75768, 6000] } )

Now, center align the column headers −

pd.set_option('display.colheader_justify', 'center') 

Example

Following is the code −

import pandas as pd # Create DataFrame dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'], "Reg_Price": [7000.5057, 1500, 5000.9578, 8000, 9000.75768, 6000] } ) print"DataFrame ...\n",dataFrame pd.set_option('display.colheader_justify', 'center') print"\nUpdated dataframe with center aligned column headers...\n", dataFrame 

Output

This will produce the following output −

DataFrame ...          Car   Reg_Price 0       BMW   7000.50570 1     Lexus   1500.00000 2     Tesla   5000.95780 3   Mustang   8000.00000 4  Mercedes   9000.75768 5    Jaguar   6000.00000 Updated dataframe with center aligned column headers...         Car Reg_Price 0       BMW 7000.50570 1     Lexus 1500.00000 2     Tesla 5000.95780 3   Mustang 8000.00000 4  Mercedes 9000.75768 5    Jaguar 6000.00000
Updated on: 2021-09-16T08:48:12+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements