As mentioned in the title, I am getting an IndexError when iterating through a n-dimensional array. What I am trying to do with the code, is to set portions of the matrix to 0 and keep the rest of the data.
I also realize that selecting an element in a n-dimensional array should be array[row#][column#] but it is just a problem with my naming convention which I will fix later. However, the values are correct.
currentMatrix = np.array(ast.literal_eval(safety.iloc[i]), dtype=np.int)
currentMatrix.shape = (27,15)
tpHeight = int(df['touchH'].iloc[i])
tpWidth = int(df['touchW'].iloc[i])
fullRows = np.arange(15)
fullColumns = np.arange(27)
beforeAreaColumns = np.arange(df['touchX'].iloc[i] - 1, dtype=np.int)
afterAreaColumns = np.arange(df['touchX'].iloc[i] + tpWidth - 1, dtype=np.int)
beforeAreaRows = np.arange(df['touchY'].iloc[i] - 1, dtype=np.int)
afterAreaRows = np.arange(df['touchY'].iloc[i] + tpHeight - 1, dtype=np.int)
print beforeAreaColumns #returns [0 1 2 3 4 5] at i = 0
currentMatrix[beforeAreaColumns][fullRows] = 0
currentMatrix[afterAreaColumns][fullRows] = 0
currentMatrix[fullColumns][beforeAreaRows] = 0
currentMatrix[fullColumns][afterAreaRows] = 0
The error I receive is:
IndexError Traceback (most recent call last)
<ipython-input-114-342e7c1b89ae> in <module>()
26 print beforeAreaColumns
27
---> 28 currentMatrix[beforeAreaColumns][fullRows] = 0
29 currentMatrix[afterAreaColumns][fullRows] = 0
30 currentMatrix[fullColumns][beforeAreaRows] = 0
IndexError: index 6 is out of bounds for axis 0 with size 6
From my understanding, I am getting the error because the code tries to find an index in position 7 when there are only 6 positions. However, I am not sure why it tries index 6 when the array stops at index 5.
I tried changing the code so that it uses for loops, for example:
for beforeAreaColumn in beforeAreaColumns:
for fullRow in fullRows:
currentMatrix[beforeAreaColumn][fullRow] = 0
but I get the same error. The above code is written and run on Python 2.7.
Related
I have this sequence:
Dataframe sequence.
And the result that I expect is:
Sequence order.
It should be finished with the last row with: 5816993 - 0
I have 3 different dataframes where I shoud apply the same order, the only thing that I know is the finish of the sequence [5816993 - 0]
Dataframe:
df_1['IN'] = [5797067,5801307,5801615,5802487,5802839,5803163,5803579,5804175,5804947,5805287,5805559,5816775,5816957,5816993,5817055]
df_1['OUT'] = [5801307, 5801615, 5802487, 5802839, 5803163, 5803579,5804175, 5804947, 5805559, 5816775, 5805287, 5817055, 5816993,0,5816957]
I hope that someone can help me to find the rest part or some tips are very welcome.
Thanks guys!!
I only can get the part of the end [5816993 - 0]
With this code:
for i, row in df_1.iterrows():
if df_2.empty:
x = df_1.loc[df_1['OUT'] == 0]
df_2['IN'] = x['IN']
df_2['OUT'] = x['OUT']
print('Estoy con DF Vacio {}'.format(i))
else:
pass
Are you looking for an overall order that is consistent with each row's IN --> OUT constraint?
If that is the case, then it is a good job for topological_sort.
With this:
r = topological_sort(df[['IN', 'OUT']].values.tolist())
>>> r
Results(sorted=[
5797067, 5801307, 5801615, 5802487, 5802839, 5803163,
5803579, 5804175, 5804947, 5805559, 5805287, 5816775,
5817055, 5816957, 5816993, 0], cyclic=[])
# since there are no cycles, we can do:
assert not r.cyclic
ix = pd.Index(r.sorted, name='IN').intersection(df['IN'])
dfnew = df.set_index('IN').reindex(ix).reset_index()
>>> dfnew
IN OUT
0 5797067 5801307
1 5801307 5801615
2 5801615 5802487
3 5802487 5802839
4 5802839 5803163
5 5803163 5803579
6 5803579 5804175
7 5804175 5804947
8 5804947 5805559
9 5805559 5805287
10 5805287 5816775
11 5816775 5817055
12 5817055 5816957
13 5816957 5816993
14 5816993 0
My code is as follows:
environment_rows = 3 #1
look_up_tables = [np.zeros((environment_rows, 20)) for _ in range(35)]
def get_starting_look_up_table(): #2
current_look_up_table = np.random.randint(35)
return current_look_up_table
def get_next_action(number_of_look_up_table,current_row_index,epsilon):
if np.random.random() < epsilon:
result=np.argmax(look_up_tables[number_of_look_up_table][current_row_index])
else: #choose a random action
result=np.random.randint(20)
return result
number_of_look_up_table = get_starting_look_up_table() #3
current_row_index = 0
epsilon = 0.9
action_index = get_next_action(current_row_index,number_of_look_up_table,epsilon)
In the first part, I produce the matrix related to look_up_tables, each of the arrays has three rows and twenty columns. We have a total of 35 of these arrays.
In the second part, using the 'get_starting_look_up_table' function, one of 35 is randomly selected. Also, by using the 'get next action' function, one of the 20 columns of the array selected by the previous function should be selected based on the largest value or randomly.
Finally, the functions are called in the third part, but I get the following error. When I run the line with the error separately, I don't have any problems. Thank you for guiding me in this regard.
IndexError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_28528/1385508929.py in <module>
2 current_row_index = 0
3
----> 4 action_index = get_next_action(current_row_index,number_of_look_up_table,epsilon)
5
6 reward = determine_rewards(number_of_look_up_table,current_row_index,action_index)
~\AppData\Local\Temp/ipykernel_28528/255015173.py in
get_next_action(number_of_look_up_table, current_row_index, epsilon)
9 def get_next_action(number_of_look_up_table,current_row_index,epsilon):
10 if np.random.random() < epsilon:
---> 11 return np.argmax(look_up_tables[number_of_look_up_table][current_row_index])
12 else: #choose a random action
13 return np.random.randint(20)
IndexError: index 27 is out of bounds for axis 0 with size 3
Your function call get_next_action(current_row_index, number_of_look_up_table, epsilon)
has the parameters in the wrong order. You switched current_row_index and number_of_look_up_table.
I think you want this:
action_index = get_next_action(number_of_look_up_table, current_row_index, epsilon)
How do I find the rows(indices) of my array, where its values change?
for example I have an array:
0 -0.638127 0.805294 1.30671
1 -0.638127 0.805294 1.30671
2 -0.085362 0.523378 0.550509
3 -0.085362 0.523378 0.550509
4 -0.323397 0.94502 0.49001
5 -0.323397 0.94502 0.49001
6 -0.323397 0.94502 0.49001
7 -0.291798 0.421398 0.962115
I want a result like:
[0 2 4 7]
I am happy to use existing librarys and I am not limited to anything. All I want are the numbers of the rows. How would I calculate that?
I tried
a = []
for i, row in enumerate(vecarray):
if i > 0:
a[i] = vecarray[i] - vecarray[i-1]
b = np.where(a != 0)
but that gives me IndexError: list assignment index out of range
arr = [
(-0.638127, 0.805294, 1.30671),
(-0.638127, 0.805294, 1.30671),
(-0.085362, 0.523378, 0.550509),
(-0.085362, 0.523378, 0.550509),
(-0.323397, 0.94502, 0.49001),
(-0.323397, 0.94502, 0.49001),
(-0.323397, 0.94502, 0.49001),
(-0.291798, 0.421398, 0.962115)
]
i = 0
prev_t = None
for t in arr:
if t != prev_t:
prev_t = t
print(i)
i += 1
I am currently finishing a hackerrank challenge. The solution I wrote works for half the test but fail for the other tests. I noticed that when manually adding the numbers, it does not equal to the expected answer. For example, in the test data below, I can't find any combinations that adds to the expected output.
I tried debugging it manually and using pdb but I do not recognize the problem.
Here is the test data :
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 9 2 -4 -4 0
0 0 0 -2 0 0
0 0 -1 -2 -4 0
Here is the expected output :
13
Here is the script :
#!/bin/python3
def get_hourglasses(array):
hourglasses = list()
row_list = list()
# Extract rows
for row in range(len(array)):
for col in range(len(array[row])):
try:
to_append = [array[row][col], array[row][col+1], array[row][col+2]]
row_list.append(to_append)
except IndexError:
break
# Construct hourglass
for row in range(len(row_list)):
try:
hourglass = [row_list[row], row_list[row+4], row_list[row+8]]
hourglasses.append(hourglass)
except:
break
return hourglasses
def get_maximum_hourglass_sum(array):
hourglass_sums = list()
hourglasses = get_hourglasses(array)
# add all the hourglasses
sums = int()
for hourglass in hourglasses:
hourglass_sums.append(sums)
sums = 0
for row in hourglass:
sums += sum(row)
return sorted(hourglass_sums)[-1]
if __name__ == '__main__':
arr = []
for _ in range(6):
arr.append(list(map(int, input().rstrip().split())))
print(get_maximum_hourglass_sum(arr))
I agree with #Barmar, and thus I understand your misunderstanding.
However, correct me if I'm wrong but I have some doubts about your get_maximum_hourglass_sum function because it seems to me that you are actually taking all of the middle row of an hourglass into account (instead of taking only the middle point)
PS : I ran your code on hackerank and I failed most of the test due to RunTimeError though
I am really
new to python. I am getiing an error stating Indexerror list index out of range. Kindly help me out. Thanks in advance .
Edit 1
x = np.array([10,0])
Phi = np.array([[ 1. , 0.01],
[ 0. , 1. ]])
Gamma = np.array([[ 0.0001048 ],
[ 0.02096094]])
Z = np.array([[ 0.0001048 ],
[ 0.02096094]])
wd = 0
u_new = 0
x1d = 0
x2d = 0
xd = [[0 for col in range(len(x))] for row in range(1000)]
xd[0][0] = 10
xd[1][0] = 0
k = 10
DistPeriodNo1 = 500
FirstPeriod = 1
k=k+1 #Update PeriodNo(so PeriodNo is now equal to No. of current period)
if (k == 100): #If maximum value of PeriodNo is reached,
k = 11 #set it to 1
DistPeriodNo1 = random.randint(11,99)
if (FirstPeriod == 0):
if (k == DistPeriodNo1):
wd = random.randint(-1,1)
else:
wd = 0
xd[0][k] = Phi*xd[0][k-1] - Gamma*u_new + Z*wd
# >>indexerror list index out of range
xd[1][k] = Phi*xd[1][k-1] - Gamma*u_new + Z*wd
x1d = xd[0][k]
x2d = xd[1][k]
To answer your question in the comments about tracebacks (stack traces): running the following
a = [1,2,3]
b = [True, False]
print(a[2])
print(b[2])
produces one answer and one traceback.
>>>
3
Traceback (most recent call last):
File "C:\Programs\python34\tem.py", line 4, in <module>
print(b[2])
IndexError: list index out of range
The traceback shows what line and what code raised the error. People were asking you to copy the last 4 line and paste them into your question (by editing it).