You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对seaborn catplot的Type排序及提取MultiIndex索引

问题解答

1. 让sns.catplot的x轴Type按Avg_Price_sqm从高到低排序

先对typecity数据按Avg_Price_sqm降序排序,再将Type列设置为分类类型并指定排序后的唯一值顺序,seaborn就会按这个顺序渲染x轴:

# 按Avg_Price_sqm降序排序数据
typecity_sorted = typecity.sort_values('Avg_Price_sqm', ascending=False)
# 设置Type的分类顺序为排序后的唯一值
typecity_sorted['Type'] = pd.Categorical(typecity_sorted['Type'], categories=typecity_sorted['Type'].unique(), ordered=True)
# 绘制柱状图
sns.catplot(data=typecity_sorted, kind='bar', y='Avg_Price_sqm', x='Type')
plt.xticks(rotation=90)
plt.show()

2. 提取MultiIndex的索引为独立列表

针对bytypecity的MultiIndex,有两种常用方法提取各层级的独立列表:

  • 方法一:直接用MultiIndex的get_level_values方法
# 提取第一个层级(Type)的索引列表
type_list = bytypecity.index.get_level_values('Type').tolist()
# 提取第二个层级(City)的索引列表
city_list = bytypecity.index.get_level_values('City').tolist()
  • 方法二:先重置索引,再取对应列转列表
# 重置索引后得到包含Type和City列的DataFrame
temp_df = bytypecity.reset_index()
type_list = temp_df['Type'].tolist()
city_list = temp_df['City'].tolist()

内容的提问来源于stack exchange,提问作者antobzzll

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 16:36:23