如何对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
相关产品推荐
相关产品推荐

