I have 2 arrays: bot
and top
, and an image
. I need to loop over the array, and for each pair of (bot,top)
,I need to fill column 3 * i + 1
from rows bot[i]
to top[i]
with 255.
I want to use vectorized code instead of a for loop to make it faster. I’ve tried some array indexing, but I don’t know the correct syntax.
How should I change the code below?
import numpy as np
import pandas as pd
N = 100
image = np.zeros((32, 32))
np.random.seed(42)
data = {
'Bot': np.array([2, 5, 3, 1, 7], dtype=np.int32),
'Top': np.array([3, 6, 4, 2, 10], dtype=np.int32)
}
# I don't have access to data, just df
df = pd.DataFrame(data)
value = 255
for i in range(len(data)):
image[df.loc[i]['Bot'] : df.loc[i]['Top'] + 1, 3 * i + 1] = value
image2 = np.zeros((32, 32))
image2[df['Bot'] : df['Top'] + 1, np.arange(len(df)) * 3 + 1] = value # error on this line
print(image == image2)
Running the code above, I have this error
ERROR!
Traceback (most recent call last):
File "<string>", line 24, in <module>
TypeError: slice indices must be integers or None or have an __index__ method