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

跟随Streamlit教程遇AttributeError:list无groupby属性问题求助

问题原因及解决办法

出现AttributeError: 'list' object has no attribute 'groupby'的核心原因是你代码里的df实际是个列表,而非Pandas的DataFrame,所以没法调用groupby方法。具体问题和修复步骤如下:

1. 函数缩进错误

你的load_data函数定义前有多余缩进,这会导致Python无法正确识别这个被@st.cache装饰的函数,可能引发后续返回值异常。修正后的代码应该把函数顶格写:

import streamlit as st
import pandas as pd    

@st.cache
def load_data():
    url = 'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'
    html = pd.read_html(url, header = 0)
    df = html[0]
    return df

df = load_data()
# 注意:groupby返回的是GroupBy对象,若要查看结果需配合聚合操作,比如统计每组数量
df_grouped = df.groupby('GICS Sector').size()

2. Streamlit缓存未更新

如果之前你修改过load_data函数(比如曾经直接返回html列表而非html[0]),Streamlit的缓存会保留旧的返回值,导致现在df还是列表。解决办法:

  • 在应用页面右上角的三点菜单里选择「Clear cache」
  • 或者重启应用时加上清除缓存参数:streamlit run 你的应用文件名.py --clean-cache

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 19:15:23