【问题标题】:python: AttributeError: 'list' object has no attribute 'groupby'python: AttributeError: \'list\' 对象没有属性 \'groupby\'
【发布时间】:2022-12-04 21:17:30
【问题描述】:

我正在关注关于 streamlit 应用程序的 Youtube 教程,但是错误

“AttributeError:‘list’对象没有属性‘groupby’”

发生在我试图对从维基百科中抓取的列表进行分组时,讲师拥有与我完全相同的代码,但没有遇到问题,我到底错过了什么?

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()
    df = df.groupby('GICS Sector')

【问题讨论】:

    标签: python pandas streamlit


    【解决方案1】:

    错误消息“AttributeError: 'list' object has no attribute 'groupby'”表示您正在尝试对列表对象使用 groupby 方法,但 groupby 方法仅适用于 Pandas DataFrame 对象。

    要修复此错误,您需要确保代码中的 html 变量包含 Pandas DataFrame,而不是 DataFrame 列表。在您的代码中, html 变量被分配给 pd.read_html 方法的结果,该方法返回一个数据帧列表。要修复错误,您需要从列表中提取所需的 DataFrame 并将其分配给 df 变量。

    以下是如何修复错误的示例:

    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)
        # Extract the DataFrame from the list and assign it to the df variable
        df = html[0]
        return df
    
    df = load_data()
    # Use the groupby method on the DataFrame
    df = df.groupby("GICS Sector")
    

    在上面的代码中,我们从 read_html 方法返回的 DataFrame 列表中提取出我们想要的 DataFrame 并将其赋值给 df 变量。然后我们可以使用 DataFrame 上的 groupby 方法按 GICS 扇区对数据进行分组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-15
      • 1970-01-01
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2014-09-08
      相关资源
      最近更新 更多