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

Pandas报错No axis named URL for object type DataFrame如何解决?

报错根因
  • 核心错误是你调用pandas的loc/iloc取数时误用了圆括号()而非方括号[]:pandas中loc后接圆括号是传入axis(轴)参数,in_stock.loc(0)是把0指定为轴参数,后续再传("URL")就会尝试查找名为URL的轴,自然触发“No axis named URL”报错。
  • 补充两个隐式bug:一是筛选DataFrame时用了链式索引,易触发SettingWithCopyWarning;二是第一段代码存在缩进错误、变量名大小写不匹配问题,运行也会抛异常。
修正方案
  1. 先修正第一段代码的缩进和变量名问题:
import pandas as pd
rows_processed=[]
for item in items.findAll("div", {"class": "item-cell"}):
    itemTitle = item.find("a", {"class": "item-title"})
    itemPromo = item.find("p", {"class": "item-promo"})
    itemPrice = item.find("li", {"class": "price-current"})
    # 下面的row逻辑要缩进进for循环内部
    row = []
    row.append(itemTitle.text)
    row.append(itemPromo.text) # 原代码写的itempromo,和上面定义的变量名大小写不匹配
    row.append(itemPrice.text)
    row.append(itemTitle.get("href"))
    rows_processed.append(row)

df = pd.DataFrame.from_records(rows_processed, columns=["Item Title ", "Status", "Price", "URL"])
  1. 再修正第二段代码的取数逻辑,直接按条件筛选后取第一条的URL值即可:
while True:
    try:
        url = "https://url.ca" 
        items = check_for_stock(url)
        # 合并筛选条件,避免链式索引
        in_stock = df.loc[(df['Price'] <= 270.00) & (df['Status'] == "Available")]
        if not in_stock.empty:
            # 用iloc[0]取第一行,方括号取URL列的值
            target_url = in_stock.iloc[0]['URL']
            buyItem(target_url)
            break
    # 注意原代码漏了except块,按需补充即可
    except Exception as e:
        pass

如果需要先拿到单行数据再取URL,写法为:

item_to_purchase = in_stock.iloc[0]
buyItem(item_to_purchase['URL'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 15:06:04