2017-10-09 59 views
2

這個問題給出了排序y軸的解決方案:Data order in seaborn heatmap from pivot 但是如何對x軸和y軸執行自定義排序?如何對索引DataFrame上的x軸和y軸執行自定義排序以獲取熱圖?

沒有自定義排序,我們看到訂單:

  • x軸:電話,電視
  • y軸:蘋果,谷歌,三星

代碼:

lol = [['apple', 'phone', 10], ['samsung', 'tv', 20], ['apple', 'tv', 5], ['google', 'tv', 8], ['google', 'phone', 9], ['samsung', 'phone', 3]] 
df = pd.DataFrame(lol) 
df = df.rename(columns={0:'brand', 1:'product', 2:'count'}) 
df = df.pivot('brand', 'product', 'count') 
ax = sns.heatmap(df) 
plt.show() 

[OUT]:

enter image description here

如果我需要排序的y軸顯示的順序samsung, apple, google,我可以這樣做:

lol = [['apple', 'phone', 10], ['samsung', 'tv', 20], ['apple', 'tv', 5], ['google', 'tv', 8], ['google', 'phone', 9], ['samsung', 'phone', 3]] 
df = pd.DataFrame(lol) 
df = df.rename(columns={0:'brand', 1:'product', 2:'count'}) 
df = df.pivot('brand', 'product', 'count') 

df.index = pd.CategoricalIndex(df.index, categories= ["samsung", "apple", "google"]) 
df.sortlevel(level=0, inplace=True) 
ax = sns.heatmap(df) 
plt.show() 

[出]:

enter image description here

但是如何對x軸和y軸執行自定義排序?,例如

  • y軸顯示順序samsung, apple, google
  • x軸顯示順序tv, phone(不只是顛倒順序)

回答

2

我認爲你可以使用reindex

a = ['samsung', 'apple', 'google'] 
b = ['tv','phone'] 

df = df.pivot('brand', 'product', 'count') 
df = df.reindex(index=a, columns=b) 
print (df) 
product tv phone 
brand    
samsung 20  3 
apple  5  10 
google 8  9 

ordered categorical

df['brand'] = df['brand'].astype('category', categories=a, ordered=True) 
df['product'] = df['product'].astype('category', categories=b, ordered=True) 

df = df.pivot('brand', 'product', 'count') 
print (df) 
product tv phone 
brand    
samsung 20  3 
apple  5  10 
google 8  9 

ax = sns.heatmap(df) 
plt.show()