python - 如何对热图的索引 DataFrame 上的 x 轴和 y 轴执行自定义排序?

标签 python pandas pivot seaborn categorical-data

这道题给出了对y轴进行排序的解决方案:Data order in seaborn heatmap from pivot 但是如何对 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()

[输出]:

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(不仅仅是颠倒顺序)

最佳答案

我想你可以使用 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()

关于python - 如何对热图的索引 DataFrame 上的 x 轴和 y 轴执行自定义排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46641618/

相关文章:

oracle11g - Oracle - 返回总和以及旋转总和?

sql - SQL Server 中的逆透视表

sql - 使用 PIVOT 函数 (Oracle) 的行到列

python - App Engine 套接字参数无效

python - 使用 QsciScintilla.findNext 向后搜索无法按预期工作

python - 使用 2 个复合索引对 Pandas DataFrame 进行切片

python - 检测 DataFrame 中某些列中的重复项并对这些列执行操作

python - 如何在Python中使用列表对字典进行排序

python - Pandas 添加两个多索引数据帧

python - 创建相关的 pandas 系列