首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >KeyError:“[列]中没有[索引([‘URL’],dtype='object')]”

KeyError:“[列]中没有[索引([‘URL’],dtype='object')]”
EN

Stack Overflow用户
提问于 2021-10-20 15:37:09
回答 1查看 40关注 0票数 0

我正在尝试使用谷歌索引API来索引我的网站网址通过python。我对编码不太了解,所以我从一个网站上复制了这段代码。

当我搜索这个错误代码之前,它似乎有一些csv格式可能有问题?

我的csv格式为"url“,然后是新行(第二列为空)。

代码如下:

代码语言:javascript
运行
复制
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
import json

import pandas as pd

# https://developers.google.com/search/apis/indexing-api/v3/prereqs#header_2
JSON_KEY_FILE = "/content/astute-tractor-329613-1baed60ec1c0.json"
SCOPES = ["https://www.googleapis.com/auth/indexing"]

credentials = ServiceAccountCredentials.from_json_keyfile_name(JSON_KEY_FILE, scopes=SCOPES)
http = credentials.authorize(httplib2.Http())

def indexURL(urls, http):
    # print(type(url)); print("URL: {}".format(url));return;

    ENDPOINT = "https://indexing.googleapis.com/v3/urlNotifications:publish"
    
    for u in urls:
        # print("U: {} type: {}".format(u, type(u)))
    
        content = {}
        content['url'] = u.strip()
        content['type'] = "URL_UPDATED"
        json_ctn = json.dumps(content)    
        # print(json_ctn);return
    
        response, content = http.request(ENDPOINT, method="POST", body=json_ctn)

        result = json.loads(content.decode())

        # For debug purpose only
        if("error" in result):
            print("Error({} - {}): {}".format(result["error"]["code"], result["error"]["status"], result["error"]["message"]))
        else:
            print("urlNotificationMetadata.url: {}".format(result["urlNotificationMetadata"]["url"]))
            print("urlNotificationMetadata.latestUpdate.url: {}".format(result["urlNotificationMetadata"]["latestUpdate"]["url"]))
            print("urlNotificationMetadata.latestUpdate.type: {}".format(result["urlNotificationMetadata"]["latestUpdate"]["type"]))
            print("urlNotificationMetadata.latestUpdate.notifyTime: {}".format(result["urlNotificationMetadata"]["latestUpdate"]["notifyTime"]))

"""
data.csv has 2 columns: URL and date.
I just need the URL column.
"""
csv = pd.read_csv("/content/indekseerida-1.csv")
csv[["URL"]].apply(lambda x: indexURL(x, http))

它给了我以下错误:

代码语言:javascript
运行
复制
KeyError                                  Traceback (most recent call last)
<ipython-input-8-f2bea693a148> in <module>()
     44 """
     45 csv = pd.read_csv("/content/indekseerida-1.csv")
---> 46 csv[["URL"]].apply(lambda x: indexURL(x, http))

/usr/local/lib/python3.7/dist-packages/pandas/core/frame.py in __getitem__(self, key)
   2910             if is_iterator(key):
   2911                 key = list(key)
-> 2912             indexer = self.loc._get_listlike_indexer(key, axis=1, raise_missing=True)[1]
   2913 
   2914         # take() does not accept boolean indexers

/usr/local/lib/python3.7/dist-packages/pandas/core/indexing.py in _get_listlike_indexer(self, key, axis, raise_missing)
   1252             keyarr, indexer, new_indexer = ax._reindex_non_unique(keyarr)
   1253 
-> 1254         self._validate_read_indexer(keyarr, indexer, axis, raise_missing=raise_missing)
   1255         return keyarr, indexer
   1256 

/usr/local/lib/python3.7/dist-packages/pandas/core/indexing.py in _validate_read_indexer(self, key, indexer, axis, raise_missing)
   1296             if missing == len(indexer):
   1297                 axis_name = self.obj._get_axis_name(axis)
-> 1298                 raise KeyError(f"None of [{key}] are in the [{axis_name}]")
   1299 
   1300             # We (temporarily) allow for some missing keys with .loc, except in

KeyError: "None of [Index(['URL'], dtype='object')] are in the [columns]"
EN

Stack Overflow用户

发布于 2021-10-20 16:53:39

为了修复这个错误,您可以替换

代码语言:javascript
运行
复制
csv[["URL"]].apply(lambda x: indexURL(x, http))

使用

代码语言:javascript
运行
复制
indexURLNew = lambda x: indexURL(x, http)
result_iterator = map(indexURLNew, csv["URL"])
print(list(result_iterator))

result_iterator是一个迭代器,您可以从中获得结果

票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69649022

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档