【问题标题】: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 以及预期输出将显着提高回答此问题的能力。

标签: pandas selenium average mean


【解决方案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

【讨论】:

    猜你喜欢
    • 2023-02-17
    • 2018-01-29
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 2017-01-28
    • 1970-01-01
    • 2020-04-26
    相关资源
    最近更新 更多