2016-12-06 373 views
1

我正在使用Jupyter筆記本,並希望顯示一個pandas DataFrame,它將相同的寬度應用於所有列,所有值居中。實現這一目標的最簡單方法是什麼,無需導入庫?Jupyter中的Pandas DataFrames:等寬和居中的列

import pandas as pd 
raw_data = {'regiment': ['Nighthawks', 'Dragoons'], 
    'company': ['1st', '2nd'], 
    'name': ['Miller', 'Jacob'], 
    'preTestScore': [4, 24], 
    'postTestScore': [25, 94]} 
df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 'preTestScore', 'postTestScore']) 
df 

Unaligned columns

+1

請不要張貼代碼爲圖像。 –

回答

3

新的大熊貓0.17.1是pd.Styler

raw_data= {'regiment': ['Nighthwawks','Dragons'], 
      'company':['1st','2nd'], 
      'name':['Miller', 'Ali'], 
      'preTestScore':[4,120]} 
df = pd.DataFrame(raw_data) 

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

我剛剛建議你也回答這個[可能的重複](http://stackoverflow.com/questions/18876022/how-to-format-ipython-html-display-of-pandas-dataframe),但我看到你已經做了。 Upvoted! – IanS

+0

謝謝@Julien,這正是我所需要的。 PS:我試圖添加代碼,但無法找到顯示輸出的方式。這是我第一次使用stackoverflow。建議最受歡迎。 – CarlosE

+1

將輸出格式化爲代碼(縮進4個空格)。通常'print(df)'將完成這項工作,只需複製並粘貼,然後選擇你的行並點擊'{}'或按'CTRL' +'K' –

相關問題