2016-06-11 93 views
0

我正在創建一個數據幀,然後將該數據幀轉換爲數據透視表。數據透視表中的文本和列標題對齊,以便在我的結果中居中。我想將文字對齊設置爲「左」。你能幫忙嗎?我試過df.to_string(justify = 'true')但它拋出一個屬性錯誤"'Unicode' object has no attribute 'columns'"熊貓數據透視表上的文本格式

這是我的數據框:

df = DataFrame({'Customer': CustomerCOL,'Title': titleCOL,'count':countCOL}) 
table = pivot_table(df,index = ['Customer','Title'],values='count') 
+0

你這是什麼正確的意思是「文本」?你可以發佈你不喜歡的輸出並嘗試顯示你想要的輸出嗎?你的解釋不足以給你一個答案。 –

+0

嗨喬,通過文本我的意思是在Excel單元格中的數據。例如:在我將數據幀轉換爲數據透視表之後。我正在將數據寫回excel。在Excel方面,數據的理由或對齊是「中心」。我想將數據對齊到「左」。這有幫助嗎?我試圖附上一個樣本數據與當前和預期的輸出,但我沒有看到這裏的附件選項。 – user3063530

回答

0

我想你需要設置參數justifyleftto_string

import pandas as pd 

df = pd.DataFrame({'Customer': ['Ann Green', 'Joseph Smith', 'Ann Green'], 
       'Title': ['Ms', 'Mr', 'Ms'], 
       'count':[4, 6, 7]}) 
print (df) 
     Customer Title count 
0  Ann Green Ms  4 
1 Joseph Smith Mr  6 
2  Ann Green Ms  7 

table = pd.pivot_table(df,index = ['Customer','Title'],values='count').reset_index() 
print (table) 
     Customer Title count 
0  Ann Green Ms 5.5 
1 Joseph Smith Mr 6.0 

print (table.to_string(justify = 'left')) 
    Customer  Title count 
0  Ann Green Ms 5.5 
1 Joseph Smith Mr 6.0 
+0

嗨,感謝您的回覆,左側的「display.colheader_justify」僅適用於列標題而非實際數據。 – user3063530

+0

請參閱編輯。 – jezrael

+0

嘿,再次感謝,我試過,但遇到這個錯誤「如果len(to_filter) user3063530