gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:24:05 29 4
gpt4 key购买 nike

这道题给出了对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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com