strix62
strix62

Reputation: 1

pandas .loc stops working when imbedded in loop

import requests
import json
import pandas as pd

CSV_output_df = pd.read_csv('output/DEMO_CSV.csv', index_col=None)
payload = {}
headers = {
  'Authorization': 'Basic ***********************************************************'
}

for index, row in CSV_output_df.iterrows():
    Package_label = CSV_output_df.loc[index, "Package Id"]
    licenseNumber = CSV_output_df.loc[index, "licenseNumber"]
    Package_label = str(Package_label)
    licenseNumber = str(licenseNumber)
    url = ("https://api-mi.metrc.com/packages/v1/" + Package_label + "?licenseNumber=" + licenseNumber)
    response = requests.request("GET", url, headers=headers, data=payload)
    json_data = (response.text.encode('utf8'))
    json_data = str(json_data)
    json_data = (json_data.strip('b'))
    json_data = (json_data.strip("'"))
    json_data = (json_data.strip('{'))
    json_data = (json_data.strip('}'))
    json_data = (json_data.replace('"Item":{', ''))
    json_data = (json_data.split(','))
    json_data_df = pd.DataFrame(json_data)
    Id = json_data_df.loc[0, 0]
    Id = Id.replace('"Id":', '')
    CSV_output_df.loc[index, "api_id"] = Id

for index, row in CSV_output_df.iterrows():
    api_id = CSV_output_df.loc[index, "api_id"]
    licenseNumber = CSV_output_df.loc[index, "licenseNumber"]
    api_id = str(api_id)
    licenseNumber = str(licenseNumber)
    url0 = ("https://api-mi.metrc.com/labtests/v1/results?packageId=" + api_id + "&licenseNumber=" + licenseNumber)
    response0 = requests.request("GET", url0, headers=headers, data=payload)
    json_data0 = (response0.text.encode('utf8'))
    json_data0 = str(json_data0)
    json_data0 = (json_data0.strip('b'))
    json_data0 = (json_data0.strip("'"))
    json_data0 = (json_data0.strip('{'))
    json_data0 = (json_data0.strip('}'))
    json_data0 = (json_data0.strip('['))
    json_data0 = (json_data0.strip(']'))
    json_data0 = (json_data0.split(','))
    json_data_df0 = pd.DataFrame(json_data0)
    data_point = (json_data_df0.loc[1187, 0])

Python noobie here and 1st-time poster. So the issue is, below command not working in my for loop but is working as a standalone command.

data_point = (json_data_df0.loc[1187, 0])

The traceback log is telling me

ValueError: 1187 is not in range

but there are 1326 rows in json_data_df0 and all values except 0, 0 do not work in the loop.

Upvotes: 0

Views: 241

Answers (1)

Jae
Jae

Reputation: 24

I think you are supposed to use .iloc if you want to access the columns/rows using integer. .loc is for accessing columns/rows using the label.

For your reference: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html

Upvotes: 1

Related Questions