Python for loop error "index out of bounds" - python

I am trying to iterate through dataframe rows and set a new column to either a 1 or 0 depending on conditions. Up to the if statement works fine, but once the elif section is added it gives me an "index out of bounds error". Any ideas on how to remedy this?
low=history.low
high = history.high
history['bottom'] = " "
history['top']=" "
for i in range(len(history)):
if (low[i] < low[i-1]) and (low[i] < low[i-2]) and (low[i] < low[i+1]) and (low[i] < low[i+2]) :
history['bottom'][i] = 1
elif (high[i] > high[i-1]) and (high[i] > high[i-2]) and (high[i] > high[i+1]) and (high[i] > high[i+2]):
history['top'][i]=1
else:
history['top'][i] = 0
history['bottom'][i] = 0

One of our error is explained by #Code-Apprentice
Other which I found and I think you are looking for this is that in lines
history['bottom'][i] = 1 and history['top'][i]=1 you are trying to change the value of an index which may not be present in it.
For example if i = 1 then the lines specified above will generate error as index 1 is not present in them. (They only have index 0).
Instead of using index to change values you can use .append to add values

It's because this is trying to access an index that doesn't exist. I would like to see more of the code above to know what history.low and history.high is referring to for the value.
But have you gotten any results before the error?
Also, please explain len(history). In your code there is a history dictionary where you have history['bottom'] = " " and history['top']=" ", but at the same time you have low=history.low and high = history.high. What's the difference between these two history objects/variables?
Please show more of your code.

Related

I keep getting "KeyError" I've tested by printing each side of the if statement but no luck

I keep getting "KeyError" I've tested by printing each side of the if statement but no luck.
def colapse():
queue = []
colapsed = random.choice(idMinEntrepy(board))
check = random.choice(range(len(board[colapsed[0]][colapsed[1]])))
board[colapsed[0]][colapsed[1]] = board[colapsed[0]][colapsed[1]][check]
queue.append(colapsed)
while len(queue)>0:
for pos in ((1,0),(0,1),(-1,0),(0,-1)):
valids = []
if -1 < queue[0][0]+pos[0] < domain[1] and -1 < queue[0][1]+pos[1] < domain[0]:
#here are my tested that did not result in the "KeyError"
#print(board[queue[0][0]][queue[0][1]][check].get("code")[yxtosideindex(pos[0],pos[1])])
#print(board[queue[0][0]+pos[0]][queue[0][1]+pos[1]][check].get("code")[yxtosideindex(pos[0], pos[1])])
# here's the issue \/ \/ \/
if board[queue[0][0]][queue[0][1]][check].get("code")[yxtosideindex(pos[0],pos[1])] == board[queue[0][0]+pos[0]][queue[0][1]+pos[1]][check].get("code")[yxtosideindex(pos[0],pos[1])]:
valids.append(board[queue[0][0]+pos[0]][queue[0][1]+pos[1]])
queue.append((queue[0][0]+pos[0],queue[0][1]+pos[1]))
board[queue[0][0]][queue[0][1]] = valids
queue.pop(0)
My code needs to compare the two and contue with the program if they are same, but i keep getting the same error. the "code" lable exists in both and the defention of both are arrays with 4 int's
ex. [100, 100, 100, 100],
[0, 1, 0, 1 ]
It looks like the KeyError is being raised when you try to access the code field of a dictionary using the get method. This error occurs when the key you are trying to access does not exist in the dictionary.
One possible cause of this error could be that the dictionary you are trying to access does not have a code key. You can fix this by adding a check to see if the code key exists in the dictionary before trying to access it:
if "code" in board[queue[0][0]][queue[0][1]][check] and "code" in board[queue[0][0]+pos[0]][queue[0][1]+pos[1]][check]:
if board[queue[0][0]][queue[0][1]][check]["code"][yxtosideindex(pos[0],pos[1])] == board[queue[0][0]+pos[0]][queue[0][1]+pos[1]][check]["code"][yxtosideindex(pos[0],pos[1])]:
valids.append(board[queue[0][0]+pos[0]][queue[0][1]+pos[1]])
Another possible cause of this error could be that the yxtosideindex function is returning a value that is not a valid index for the code list. You can fix this by adding a check to make sure that the value returned by yxtosideindex is a valid index for the code list:
index = yxtosideindex(pos[0],pos[1])
if index >= 0 and index < len(board[queue[0][0]][queue[0][1]][check]["code"]) and index >= 0 and index < len(board[queue[0][0]+pos[0]][queue[0][1]+pos[1]][check]["code"]):
if board[queue[0][0]][queue[0][1]][check]["code"][index] == board[queue[0][0]+pos[0]][queue[0][1]+pos[1]][check]["code"][index]:
valids.append(board[queue[0][0]+pos[0]][queue[0][1]+pos[1]])

How can I return a list

I wanted to do a discord command scraper in python for the raffles available on https://releases.footshop.com/ and I almost finished it but when I wan to return a list of size (and stock also) it's return an error "IndexError: list index out of range" and I can't find what to do :/
thank for your help guys !
I try this code but it return an error (I try other thing but I don't remember, I had been trying to find a solution by myself for some time now lol)
there is the code:
def searchsizefootshop(size):
item = searchfootshop(size)
if len(item['sizeSets']['Men']['sizes']) !=0:
size1 = int(item['sizeSets']['Men']['sizes'][X])
size = item['sizeSets']['Men']['sizes'][X]['eur']
count = 0
while count <= len(size1):
print(size[count])
count += 1
searchsizefootshop('hGZrRYMB3xHSyCfZ4BFw')
[scraper]
[Footshop API]
len(size1) returns the length of the list, not the index of the last item. To loop through a list using len and index access, you need to compare it to len(size1) - 1 or just use count < len(size1).

Error: '>' not supported between instances of 'method' and 'int'

This code isn't working in Jupyter IDE. I can't find my mistake. Please help.
The first 5 rows of the dataframe I am using is shown here:
Try the following:
df.loc[df['compound'] > 0,'SentimentType'] = 'Positive'
df.loc[df['compound'] < 0,'SentimentType'] = 'Negative'
df.loc[df['compound'] == 0,'SentimentType'] = 'Neutral'
Instead of retrieving the column through df.compound, you should do df['compound']. You can also tell from the error message that you received that df.compound is a method name and not the column that you are looking for.
If you are trying to compare values of 'compound' column, you must use df['compound'] instead of df.compound, which is a method.
Maybe the following code can help you:
Function to classify 'Sentiment_Type'
def sentiment(score):
if score < 0:
return "Negative"
elif score > 0:
return "Positive"
else:
return "Neutral"
After, you can use this function to create a new column
df['Sentiment_Type'] = df['compound'].apply(sentiment)
add brackets to 1 st line df.compund() >0

Unable to change value of dataframe at specific location

So I'm trying to go through my dataframe in pandas and if the value of two columns is equal to something, then I change a value in that location, here is a simplified version of the loop I've been using (I changed the values of the if/else function because the original used regex and stuff and was quite complicated):
pro_cr = ["IgA", "IgG", "IgE"] # CR's considered productive
rows_changed = 0
prod_to_unk = 0
unk_to_prod = 0
changed_ids = []
for index in df_sample.index:
if num=1 and color="red":
pass
elif num=2 and color="blue":
prod_to_unk += 1
changed_ids.append(df_sample.loc[index, "Sequence ID"])
df_sample.at[index, "Functionality"] = "unknown"
rows_changed += 1
elif num=3 and color="green":
unk_to_prod += 1
changed_ids.append(df_sample.loc[index, "Sequence ID"])
df_sample.at[index, "Functionality"] = "productive"
rows_changed += 1
else:
pass
print("Number of productive columns changed to unknown: {}".format(prod_to_unk))
print("Number of unknown columns changed to productive: {}".format(unk_to_prod))
print("Total number of rows changed: {}".format(rows_changed))
So the main problem is the changing code:
df_sample.at[index, "Functionality"] = "unknown" # or productive
If I run this code without these lines of code, it works properly, it finds all the correct locations, tells me how many were changed and what their ID's are, which I can use to validate with the CSV file.
If I use df_sample["Functionality"][index] = "unknown" # or productive the code runs, but checking the rows that have been changed shows that they were not changed at all.
When I use df.at[row, column] = value I get "AttributeError: 'BlockManager' object has no attribute 'T'"
I have no idea why this is showing up. There are no duplicate columns. Hope this was clear (if not let me know and I'll try to clarify it). Thanks!
To be honest, I've never used df.at - but try using df.loc instead:
df_sample.loc[index, "Functionality"] = "unknown"
You can also iat.
Example: df.iat[iTH row, jTH column]

Please help me better understand this one "except"conditional line

I'm about a couple weeks into learning Python.
With the guidance of user:' Lost' here on Stackoverflow I was able to figure out how to build a simple decoder program. He suggested a code and I changed a few things but what was important for me was that I understood what was happening. I understand 97% of this code except for the except: i += 1 line in the decode(). As of now the code works, but I want to understand that line.
So basically this code unscrambles an encrypted word based on a specific criteria. You can enter this sample encrypted word to try it out. "0C1gA2uiT3hj3S" the answer should be "CATS"
I tried replacing the except: i += 1 with a Value Error because I have never seen a Try/Except conditional that just had an operational and no Error clause. But replacing it with Value Error created a never ending loop.
My question is what is the purpose of writing the except: i += 1 as it is.
'Lost' if you're there could you answer this question. Sorry, about the old thread
def unscramble(elist):
answer = []
i = 0
while i <= len(elist):
try:
if int(elist[i]) > -1:
i = i + int(elist[i]) + 1
answer.append(elist[i])
except:
i += 1
return "".join(answer)
def boom():
eword = input("paste in your encrypted message here >> ")
elist = list(eword)
answer = unscramble(elist)
print (answer)
clear()
boom()
The purpose is to advance i by one, skipping the current character in case the cast to int fails, i.e. if elist[i] is not a digit.
There are a couple of errors, than can occur inside the try-Block:
i is out of index, because the while loop runs one index to far.
elist[i] is not a number, which leads to an ValueError
i = i + int(elist[i]) + 1 gets to big, and the next index access leads also to an IndexError
In either way, the except-clause will ignore the next character. And the loop goes on.
An correct implementation wouldn't need any exceptions:
def unscramble(elist):
answer = []
i = 0
while i < len(elist):
i += int(elist[i]) + 1
answer.append(elist[i])
i += 1
return "".join(answer)

Categories

Resources