如何对熊猫表中的值进行平均

Posted

技术标签:

【中文标题】如何对熊猫表中的值进行平均【英文标题】:How to do an average of values in a pandas table 【发布时间】:2021-09-09 19:36:49 【问题描述】:

这是我拥有的用于创建功能表的代码。

items = results.findAll("li")
rows=[]
for item in items: 
    titleElement = item.find("h3")
    priceElement = item.find("span", "class": "s-item__price")
    dateElement = item.find("span", "class": "POSITIVE")

    if titleElement and priceElement and dateElement:
            data = [dateElement.text, titleElement.text, priceElement.text]
            rows.append(data)
df = pd.DataFrame.from_records(rows, columns=["Purchase Date", "Title", "Price"])
df

我现在正在寻找 priceElement 值的平均值

我熟悉这个的唯一方法是通过

average = sum/len

但是当我这样做时

if priceElement:
    average = sum(priceElement)/len(priceElement)

print(average.text)

我收到错误“未定义平均值”。如何开发此代码?

【问题讨论】:

df['Price'].mean() ?您可能还需要先转换为数字类型,因为您似乎正在将值作为文本添加到 DataFrame。示例 DataFrame 以及预期输出将显着提高回答此问题的能力。 【参考方案1】:

您可以先将Price 列转换为数字,然后获取其mean 以获得平均值。

average = pd.to_numeric(df["Price"]).mean()    #If Price is number in string

或者如果价格已经是数字,那么您可以执行以下操作。

average = df["Price"].mean()    #If Price is integer or float

【讨论】:

以上是关于如何对熊猫表中的值进行平均的主要内容,如果未能解决你的问题,请参考以下文章