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

如何基于pivot_table结果绘制Top3社区堆叠柱状图并解决KeyError问题

解决步骤

1. 修复筛选逻辑

你已经明确报错是因为neighbourhood是df_new的行索引而非普通列,直接对索引做匹配筛选即可:

# 提取计数Top3的社区名称列表
top3_neighbourhoods = df_Best['neighbourhood'].tolist()
# 从pivot结果中筛选对应社区的数据
df_plot = df_new.loc[df_new.index.isin(top3_neighbourhoods)]

2. 绘制堆叠柱状图

直接基于筛选后的pivot表调用绘图方法即可,stacked=True参数指定为堆叠样式:

import matplotlib.pyplot as plt

# 设置画布大小
plt.figure(figsize=(8, 5))
# 绘制堆叠柱状图
df_plot.plot(kind='bar', stacked=True, ax=plt.gca())
# 添加图表标签
plt.xlabel('社区')
plt.ylabel('平均价格')
plt.title('Top3社区不同房型平均价格堆叠柱状图')
plt.xticks(rotation=0)
plt.legend(title='房型')
plt.show()

完整可运行代码

import pandas as pd
import matplotlib.pyplot as plt

# 示例数据
d = {'host_id': [1, 1, 2, 3, 3], 
     'listing_id': [1, 2, 3, 4, 5],
     'neighbourhood': ['Sofia', 'New York', 'Berlin', 'London', 'London'], 
     'price': [50.0, 60.0, 50.0, 80.0, 90.0], 
     'room_type': ['Private', 'Private', 'Shared', 'Private', 'Shared']}
df = pd.DataFrame(data=d)

# 生成pivot表
df_new = df.pivot_table(index='neighbourhood', columns='room_type',
                        values='price', aggfunc='mean',
                        fill_value=0.0)

# 统计各社区房源数取Top3
df_Best = df.groupby(["neighbourhood"])["room_type"].count().reset_index(
    name="count").sort_values(by=['count'], ascending=False).head(3)

# 筛选Top3社区的pivot数据
top3_neighbourhoods = df_Best['neighbourhood'].tolist()
df_plot = df_new.loc[df_new.index.isin(top3_neighbourhoods)]

# 绘图
plt.figure(figsize=(8, 5))
df_plot.plot(kind='bar', stacked=True, ax=plt.gca())
plt.xlabel('社区')
plt.ylabel('平均价格')
plt.title('Top3社区不同房型平均价格堆叠柱状图')
plt.xticks(rotation=0)
plt.legend(title='房型')
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 09:15:03