2016-12-10 53 views
0

這是問題"Pandas DataFrames in Jupyter: columns of equal width and centered"的變體。Jupyter中的Pandas DataFrames:分別格式化索引和列

我們如何顯示一個索引數據幀,其中所有列都居中,除了索引,應該對齊左邊的索引?而且,我們如何控制索引的寬度和其他屬性?

import pandas as pd 
raw_data = {'Regiment': ['Nighthawks', 'Raptors'], 
    'Company': ['1st', '2nd'], 
    'preTestScore': [4, 24], 
    'postTestScore': [25, 94]} 
df = pd.DataFrame(raw_data, columns = ['Regiment', 'Company', 'preTestScore', 'postTestScore']).set_index('Regiment') 
d = dict(selector="th", 
    props=[('text-align', 'center')]) 

df.style.set_properties(**{'width':'10em', 'text-align':'center'})\ 
     .set_table_styles([d]) 

enter image description here

回答

1

只需添加以下樣式:

style_index = dict(selector=".row_heading", props=[("text-align", "right")])

+0

謝謝。我不知道你可以在set_table_styles中有多個樣式字典。 – CarlosE

0
import pandas as pd 
raw_data = {'Regiment': ['Nighthawks', 'Raptors'], 
    'Company': ['1st', '2nd'], 
    'preTestScore': [4, 24], 
    'postTestScore': [25, 94]} 
df = pd.DataFrame(raw_data, columns = ['Regiment', 'Company', 'preTestScore', 'postTestScore']).set_index('Regiment') 
d1 = dict(selector="th", props=[('text-align', 'center')]) 
d2 = dict(selector=".row_heading", props=[("text-align", "left")]) 

df.style.set_properties(**{'width':'10em', 'text-align':'center'})\ 
     .set_table_styles([d1,d2]) 

Solution

相關問題