索引定位器错误IndexError:单个位置索引器超出范围

问题描述 投票:0回答:1

我正在编写python代码以使用gspread访问Google表格中的数据。

    import gspread
    from oauth2client.service_account import ServiceAccountCredentials
    from pprint import pprint
    import pandas as pd
    scope =['https://www.googleapis.com/auth/spreadsheets']
    creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)
    client = gspread.authorize(creds)

    sheet = client.open("tutorial") # Open the spreadhseet
    worksheet = sheet.get_worksheet(1)
    data = pd.DataFrame(worksheet.get_all_records()) 
    car = "car"
    mpg = "mpg"
    city_mpg_data = data[data['city mpg'] == mpg]
    car_city_mpg_data = city_mpg_data[city_mpg_data['Make'] == car]
    car_city_mpg_data = car_city_mpg_data.reset_index()
    get = car_city_mpg_data.iloc[2]

    print("Okay. You are looking for {} {}.".format(get[6], get[8]))

我收到错误:

IndexError:单个位置索引器超出范围。请指出我在做什么错吗?

python-3.x pandas gspread
1个回答
0
投票

IndexError: single positional indexer is out-of-bounds表示您正在尝试访问不存在的元素。

Google快速搜索发现,这是熊猫数据框iloc方法引起的错误。

[get = car_city_mpg_data.iloc[2]方法尝试访问较少的第三数据帧行。

我将在该行之前添加print(car_city_mpg_data),然后从那里进行调查。

© www.soinside.com 2019 - 2024. All rights reserved.