I have a dataframe column that I am trying to iterate through using a for loop:
So with my loop, I am using the python index to get the max value for my iteration but code runs a bit slow and prints a Key error when it reaches the last index. I am trying to loop through the dataframe column final_df["MAN"] and compare the current index with the previous index during the loop, and if it is equal put 0 in the new column created final_df["MAN_ID"] and 1 if it is not equal to.
%%time
#Sort by MAN column
final_df.sort_values(by=['MAN'])
#Loop through the column
final_df["MAN_ID"] = ""
try:
for i in final_df.index:
if final_df["MAN"][i+1] == final_df["MAN"][i]:
final_df["MAN_ID"][i] = 0
elif final_df["MAN"][i+1] != final_df["MAN"][i]:
final_df["MAN_ID"][i] = 1
except:
print("No value to loop")