jeudi 25 juillet 2019

How to iterate over rows and assign values to a new column

I have a dataframe with over 75k rows, having about 13 pre-existing columns. Now, I want to create a new column based on an if statement, such that:

if each row of a certain column has the same value as the next, then the value in the new column for that row would be 0 or 1.

The if statement checks for two equalities (columns are tags_list and gateway_id).

The below code snippet is what I have tried

for i in range(1,len(df_sort['date'])-1):

    if (df_sort.iloc[i]['tags_list'] == df_sort.iloc[i+1]['tags_list']) & (df_sort.iloc[i]['gateway_id'] == df_sort[i+1]['gateway_id']):
        df_sort.iloc[i]['Transit']=0
    else:
        df_sort.iloc[i]['Transit']=1

Getting a keyerror :2 in this case

PS: All of the columns have the same number of rows

Aucun commentaire:

Enregistrer un commentaire