2016-12-15 114 views
0

我有我的導出爲HTML大熊貓TO_HTML條件格式

enter image description here

每天透視表我使用的代碼來創建它是

HEADER = ''' 
<html> 
    <head> 
     <style> 
      .df tbody tr:last-child { background-color: #FF0000; } 
     </style> 
    </head> 
    <body> 
''' 
FOOTER = ''' 
    </body> 
</html> 
''' 

with open("/home/testing_libs/htmlex.html", 'w') as f: 
    f.write(HEADER) 
    f.write(pivot1.to_html(classes='pivot1')) 
    f.write(FOOTER) 

源是大熊貓數據幀。我想用PANDA創建邏輯,使其有一列不出現在數據透視表中,但確定單位的數據透視單元的顏色。換句話說,如果我比較今天的數據透視表,甚至是前一天的數據框,以前面的日期爲單位,而當前的日期單位越小,那麼我也希望HTML中的單元格爲「紅色」,而不是黑色。 我不知道我是否可以根據不是'單位'值的HTML顏色紅色,而是相關的正/負值比較同一組的'單位'值。 下面是創建上述數據透視表

widget region industry units 
0 oldschool middle tech 10 
1 newschool west manufacturing 40 
2 upandcomer east manufacturing 50 
3 oldschool west manufacturing 40 
4 newschool east manufacturing 30 
5 upandcomer middle manufacturing 20 
6 oldschool middle manufacturing 10 
7 newschool east tech 30 
8 upandcomer east tech 30 

然後創建PIVOT數據框

pivot1 = pd.pivot_table(frame1,index=['region','widget','industry']) 

回答

0

你可以使用np.where(condition, ifConditionTrue, ifConditionFalse)從numpy的依賴於對另一列(或系列)的比較來更新pivot1['units']哪裏您存儲前一天的單位和.map(),以ANSI colour codes爲輸出着色,例如:

pivot1['units'] = np.where((pivot1['units'] < pivot0['units']), (pivot1['units'] = pivot1['units'].map(lambda x: "\x1b[41m"+str(x)+"\x1b[m")), (pivot1['units'].map(lambda x: str(x))) 

其中pivot1是當天的數據幀,pivot0是前一天的數據幀,奇怪的前綴和後綴是紅色背景上黑色文本的ANSI顏色代碼。

但是,這將使您的'單位'整數值介紹字符串,從而使日期之間的比較不可能,除非您將它們轉換回整數 - 因此這不是在主數據框上使用的最佳策略。我建議使用不同的名稱爲HTML導出重新生成它。

pivot1_export = pivot1 
pivot1_export['units'] = np.where((pivot1['units'] < pivot0['units']), (pivot1_export['units'] = pivot1['units'].map(lambda x: "\x1b[41m"+str(x)+"\x1b[m")), (pivot1_export['units'].map(lambda x: str(x))) 

可以重複此策略,以增加更多的色彩更高,持平,或特定值。

+0

非常感謝。但我也意識到,爲了進行比較,今天/昨天的數據幀必須具有相同的大小。所以這些分組會有所不同,例如,昨天東部地區可能沒有'newschool'部件。所以目前我得到一個錯誤,ValueError:系列長度必須匹配比較 – PR102012

+0

在這個設置中,我會保持df尺寸穩定,例如。用零填充空小部件的行 - 除非它們隨着時間而不同 - 即,新來的老人走了。 – Zedelghem